一、服务端

1.新建webapi项目

2.配置WebApiConfig

public const string DEFAULT_ROUTE_NAME = "DB";// DB指数据库上下文
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DEFAULT_ROUTE_NAME",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.EnableSystemDiagnosticsTracing();
}

3.在models文件新建studentInfo模型

[Table("studentInfo")]
public class studentInfo
{
[Key]
public int Id { get; set; }
/// <summary>
/// 学号
/// </summary>
public int studentId { get; set; }
/// <summary>
/// 学生姓名
/// </summary>
public string studentName { get; set; }
/// <summary>
/// 联系方式
/// </summary>
public string contact { get; set; }
}

4.在models文件中添加DB,数据库上下文, DB要继承DbContext

public DbSet<studentInfo> sInfo { get; set; }

5.在models文件中添加接口IstudentRepository

/// <summary>
/// 获得所有人
/// </summary>
/// <returns></returns>
IEnumerable<studentInfo> GetAll();
/// <summary>
/// 根据ID查询
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
studentInfo Get(int id);
/// <summary>
/// 添加
/// </summary>
/// <param name="person"></param>
/// <returns></returns>
studentInfo Add(studentInfo info);
/// <summary>
/// 删除
/// </summary>
/// <param name="id"></param>
void Remove(int id);
/// <summary>
/// 更新
/// </summary>
/// <param name="person"></param>
/// <returns></returns>
bool Update(studentInfo info);

 6.在models文件中添加仓库实现studentRepository

public class studentRepository : IstudentRepository
{
DB db = new DB();
private List<studentInfo> _people = new List<studentInfo>();

public IEnumerable<studentInfo> GetAll()
{
var model = db.sInfo.OrderByDescending(c => c.Id).ToList();
return model;
}

public studentInfo Get(int id)
{
var queryData = db.sInfo.FirstOrDefault(c => c.Id == id);

return queryData;
}

public studentInfo Add(studentInfo info)
{
if (info == null)
{

throw new ArgumentNullException("info");

}

var addmodel = db.sInfo.Add(info);
db.SaveChanges();
return addmodel;
}

public void Remove(int id)
{

var model = db.sInfo.Find(id);
db.sInfo.Remove(model);
db.SaveChanges();

}

public bool Update(studentInfo Info)
{
if (Info == null)
{

return false;
}

else
{
var model = db.sInfo.FirstOrDefault(c => c.Id == Info.Id);
model.studentId = Info.studentId;
model.studentName = Info.studentName;
model.contact = Info.contact;
var entry = db.Entry(model);
entry.Property(c => c.studentId).IsModified = true;
entry.Property(c => c.contact).IsModified = true;

entry.Property(c => c.studentName).IsModified = true;
db.SaveChanges();

return true;
}

}
}

 7.配置web.config

<add name="DB" providerName="System.Data.SqlClient" connectionString="Data Source=.;Initial Catalog=WebApiDB;Integrated Security=SSPI; User ID=sa; password=123456" />

8.在controllers中添加apiController为PersonController

static readonly IstudentRepository databasePlaceholder = new studentRepository();
/// <summary>
/// 所有人数
/// </summary>
/// <returns></returns>
public IEnumerable<studentInfo> GetAllPeople()
{
return databasePlaceholder.GetAll();
}

/// <summary>
/// 查询
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public studentInfo GetPersonByID(int id)
{
studentInfo person = databasePlaceholder.Get(id);
if (person == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return person;
}
/// <summary>
/// 添加
/// </summary>
/// <param name="person"></param>
/// <returns></returns>
public HttpResponseMessage PostPerson(studentInfo person)
{
person = databasePlaceholder.Add(person);
string apiName = MyWebApiDemo.WebApiConfig.DEFAULT_ROUTE_NAME;
var response = this.Request.CreateResponse<studentInfo>(HttpStatusCode.Created, person);
string uri = Url.Link(apiName, new { id = person.Id });
response.Headers.Location = new Uri(uri);
return response;
}
/// <summary>
/// 更新
/// </summary>
/// <param name="person"></param>
/// <returns></returns>
public bool PutPerson(studentInfo person)
{
if (!databasePlaceholder.Update(person))
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return true;

}
/// <summary>
/// 删除
/// </summary>
/// <param name="id"></param>
public void DeletePerson(int id)
{

studentInfo person = databasePlaceholder.Get(id);

if (person == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}

databasePlaceholder.Remove(id);

}

二、客户端

private const string url = "http://localhost:50043/";
public ActionResult Index()
{
List<studentInfo> people = GetAllPerson();
return View(people);
}
/// <summary>
/// 获得所有学生信息
/// </summary>
/// <returns></returns>
static List<studentInfo> GetAllPerson()
{
HttpClient client = new HttpClient();
HttpResponseMessage response = client.GetAsync(url + "api/person").Result;
return response.Content.ReadAsAsync<List<studentInfo>>().Result;
}
public ActionResult Delete(int id)
{
DeletePerson(id);
return RedirectToAction("Index");
}
/// <summary>
/// 删除
/// </summary>
/// <param name="id"></param>
static void DeletePerson(int id)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);
var relativeUri = "api/person/" + id.ToString();
var response = client.DeleteAsync(relativeUri).Result;
client.Dispose();
}
static studentInfo GetPerson(int id)
{
HttpClient client = new HttpClient();
HttpResponseMessage response = client.GetAsync(url + "api/person/" + id).Result;

return response.Content.ReadAsAsync<studentInfo>().Result;
}

public ActionResult Update(int id)
{
studentInfo model = GetPerson(id);
return View(model);
}
[HttpPost]
public ActionResult Update(studentInfo info)
{

UpdatePerson(info);

return RedirectToAction("Index");
}

static bool UpdatePerson(studentInfo info)
{

HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);
var response = client.PutAsJsonAsync("api/person", info).Result;
bool b= response.Content.ReadAsAsync<bool>().Result;
return b;
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(studentInfo info)
{
JObject newPerson = AddPerson(info);
return RedirectToAction("Index");
}
static JObject AddPerson(studentInfo info)
{

HttpClient client = new HttpClient();

client.BaseAddress = new Uri(url);

var response = client.PostAsJsonAsync("api/person", info).Result;

return response.Content.ReadAsAsync<JObject>().Result;

}

.Net WebApi基本操作的更多相关文章

  1. Web APi入门之基本操作(一)

    最近学习了下WebApi,WebApi是RESTful风格,根据请求方式决定操作.以博客的形式写出来,加深印象以及方便以后查看和复习. 1.首先我们使用VS创建一个空的WebApi项目 2.新建实体以 ...

  2. js对WebApi请求的基本操作

    在WebAPI对外提供的,大概有4种接口,get,post,delete,put,现在,我就简单的来说一下js请求webApi的方式和大概的作用: get:在webApi中,get方法通常是用来获取数 ...

  3. WebApi初探之基本操作(CRUD)

    public class ProductsController : ApiController { static List<Product> products = new List< ...

  4. [.net 面向对象程序设计深入](6).NET MVC 6 —— 模型、视图、控制器、路由等的基本操作

    [.net 面向对象程序设计深入](6).NET MVC 6 —— 模型.视图.控制器.路由等的基本操作 1. 使用Visual Studio 2015创建Web App (1)文件>新建> ...

  5. WebAPI生成可导入到PostMan的数据

    一.前言 现在使用WebAPI来作为实现企业服务化的需求非常常见,不可否认它也是很便于使用的,基于注释可以生成对应的帮助文档(Microsoft.AspNet.WebApi.HelpPage),但是比 ...

  6. 使用ASP.Net WebAPI构建REST服务(一)——简单的示例

    由于给予REST的Web服务非常简单易用,它越来越成为企业后端服务集成的首选方法.本文这里介绍一下如何通过微软的Asp.Net WebAPI快速构建REST-ful 服务. 首先创建一个Asp.Net ...

  7. 【WebAPI No.1】创建简单的 .NETCore WebApi

    介绍: 官方定义如下,强调两个关键点,即可以对接各种客户端(浏览器,移动设备),构建http服务的框架.Web API最重要的是可以构建面向各种客户端的服务. core的WebAPI与ASP.NET ...

  8. C# WebApi使用AttributeRoutes特性路由

    1.在创建WebApi中默认的路由规则,只能满足一般简单的RESTful风格,如 api/Products/{id}. 但是在实际运用中很难严格满足RESTful要求的WebApi.因此需要使用高版本 ...

  9. WebAPI 身份认证解决方案——Phenix.NET企业应用软件快速开发平台.使用指南.21.WebAPI服务(一)

    21   WebAPI服务 ASP.NET Web API,是微软在.NET Framework 4.5上推出的轻量级网络服务框架,虽然作为ASP.NET MVC 4的一部分,但却是一套全新的.独立的 ...

随机推荐

  1. Python标准模块—Regular Expressions

    作者:zhbzz2007 出处:http://www.cnblogs.com/zhbzz2007 欢迎转载,也请保留这段声明.谢谢! 1 模块简介 正则表达式是一门小语言,你可以在Python中或者其 ...

  2. C语言中的指针

    请先看C++中的指针概述,这里只是扩充 数组指针 其实这里主要说的就是c++中的指针运算 /* 数组元素指针: 一个变量有地址,一个数组包含若干个元素,每个数组元素都有相应的地址, 指针变量可以指向数 ...

  3. phpcms页面替换

    首页的替换流程首先要先把静态网页做出来,拿到这里来: 会发现这个网页里面少了图片,样式表也没有了 因为我们只把网页扔过来,所对应的图片和样式表没有扔过来 图片什么的应该扔到: 接着打开index.ht ...

  4. pdf.js实现在HTML下直接浏览pdf文档,无需插件即可实现

    近期,有一个朋友做B端,服务器存了大量的金融类数据,很多都是pdf文档,他现在的做法是,先将pdf文档转换成flash,再放到浏览器上给用户浏览,但是他告诉我,这种体验太差了,而且很好资源,空间已经快 ...

  5. 关于SqlServer远程跨库修改数据

    今天遇到一个需求需要修改远程服务器上的数据,如何直接修改,并且垮库,跨库简单,直接加上数据库名字,远程的话则需要创建链接服务器,具体步骤如下: --创建链接服务器  exec sp_addlinked ...

  6. JavaScript之通用addLoadEvent代码源码

    在执行javascript代码时 很多情况下 我们是希望代码在网页加载完毕后立刻进行的 大家可能会立刻想到使用window.onload时间处理函数,然后通过 window.onload=functi ...

  7. OpenStack Newton版本Ceph集成部署记录

    2017年2月,OpenStack Ocata版本正式release,就此记录上一版本 Newton 结合Ceph Jewel版的部署实践.宿主机操作系统为CentOS 7.2 . 初级版: 192. ...

  8. 深度解析MySQL启动时报“The server quit without updating PID file”错误的原因

    很多童鞋在启动mysql的时候,碰到过这个错误, 首先,澄清一点,出现这个错误的前提是:通过服务脚本来启动mysql.通过mysqld_safe或mysqld启动mysql实例并不会报这个错误. 那么 ...

  9. 学习SpringMVC中优秀的代码编写风格

    在org.springframework.web.servlet.FrameworkServlet 中有下面这段代码 private class ContextRefreshListener impl ...

  10. MHA在线切换的步骤及原理

    在日常工作中,会碰到如下的场景,如mysql数据库升级,主服务器硬件升级等,这个时候就需要将写操作切换到另外一台服务器上,那么如何进行在线切换呢?同时,要求切换过程短,对业务的影响比较小. MHA就提 ...