ASP.NET WEB API入门实例

1.WebApi是什么

    ASP.NET Web API 是一种框架,用于轻松构建可以由多种客户端(包括浏览器和移动设备)访问的 HTTP 服务。ASP.NET Web API 是一种用于在 .NET Framework 上构建 RESTful 应用程序的理想平台。

    可以把WebApi看成Asp.Net项目类型中的一种,其他项目类型诸如我们熟知的WebForm项目,Windows窗体项目,控制台应用程序等。

    WebApi类型项目的最大优势就是,开发者再也不用担心客户端和服务器之间传输的数据的序列化和反序列化问题,因为WebApi是强类型的,可以自动进行序列化和反序列化,一会儿项目中会见到。

    下面我们建立了一个WebApi类型的项目,项目中对产品Product进行增删改查,Product的数据存放在List<>列表(即内存)中。

2.页面运行效果

Asp.net WebApi 项目示例(增删改查)0

如图所示,可以添加一条记录; 输入记录的Id,查询出该记录的其它信息; 修改该Id的记录; 删除该Id的记录。

3.二话不说,开始建项目

1)新建一个“ASP.NET MVC 4 Web 应用程序”项目,命名为“ProductStore”,点击确定,如图

Asp.net WebApi 项目示例(增删改查)1

扫描二维码关注公众号,回复: 3558395 查看本文章

2)选择模板“Web API”,点击确定,如图

Asp.net WebApi 项目示例(增删改查)2

3)和MVC类型的项目相似,构建程序的过程是先建立数据模型(Model)用于存取数据, 再建立控制器层(Controller)用于处理发来的Http请求,最后构造显示层(View)用于接收用户的输入和用户进行直接交互。

 

     这里我们先在Models文件夹中建立产品Product类: Product.cs,如下:


   
   
  1. using System;
  2. using System .Collections .Generic;
  3. using System .Linq;
  4. using System .Web;
  5. namespace ProductStore .Models
  6. {
  7. public class Product
  8. {
  9. public int Id { get; set; }
  10. public string Name { get; set; }
  11. public string Category { get; set; }
  12. public decimal Price { get; set; }
  13. }
  14. }

4)试想,我们目前只有一个Product类型的对象,我们要编写一个类对其实现增删改查,以后我们可能会增加其他的类型的对象,再需要编写一个对新类型的对象进行增删改查的类,为了便于拓展和调用,我们在Product之上构造一个接口,使这个接口约定增删改查的方法名称和参数,所以我们在Models文件夹中新建一个接口:  IProductRepository.cs ,如下:


   
   
  1. using System;
  2. using System .Collections .Generic;
  3. using System .Linq;
  4. using System .Text;
  5. using System .Threading .Tasks;
  6. namespace ProductStore .Models
  7. {
  8. interface IProductRepository
  9. {
  10. IEnumerable<Product> GetAll();
  11. Product Get(int id);
  12. Product Add(Product item);
  13. void Remove(int id);
  14. bool Update(Product item);
  15. }
  16. }

5)然后,我们实现这个接口,在Models文件夹中新建一个类,具体针对Product类型的对象进行增删改查存取数据,并在该类的构造方法中,向List<Product>列表中存入几条数据,这个类叫:ProductRepository.cs,如下:


   
   
  1. using System;
  2. using System .Collections .Generic;
  3. using System .Linq;
  4. using System .Web;
  5. namespace ProductStore .Models
  6. {
  7. public class ProductRepository:IProductRepository
  8. {
  9. private List<Product> products = new List<Product>();
  10. private int _nextId = 1;
  11. public ProductRepository()
  12. {
  13. Add(new Product { Name="Tomato soup",Category="Groceries",Price=1.39M});
  14. Add( new Product { Name="Yo-yo",Category="Toys",Price=3.75M});
  15. Add( new Product { Name = "Hammer", Category = "Hardware", Price = 16.99M });
  16. }
  17. public IEnumerable< Product> GetAll()
  18. {
  19. return products;
  20. }
  21. public Product Get( int id)
  22. {
  23. return products.Find(p=>p.Id==id);
  24. }
  25. public Product Add( Product item)
  26. {
  27. if (item == null)
  28. {
  29. throw new ArgumentNullException("item");
  30. }
  31. item .Id = _ nextId++;
  32. products .Add( item);
  33. return item;
  34. }
  35. public void Remove( int id)
  36. {
  37. products.RemoveAll(p=>p.Id==id);
  38. }
  39. public bool Update( Product item)
  40. {
  41. if (item == null)
  42. {
  43. throw new ArgumentNullException("item");
  44. }
  45. int index = products .FindIndex( p=> p .Id== item .Id);
  46. if ( index == -1)
  47. {
  48. return false;
  49. }
  50. products .RemoveAt( index);
  51. products .Add( item);
  52. return true;
  53. }
  54. }
  55. }

此时,Model层就构建好了。

6)下面,我们要构建Controller层,在此之前,先回顾一下Http中几种请求类型,如下

 

     get  类型  用于从服务器端获取数据,且不应该对服务器端有任何操作和影响

     post 类型  用于发送数据到服务器端,创建一条新的数据,对服务器端产生影响

     put 类型  用于向服务器端更新一条数据,对服务器端产生影响 (也可创建一条新的数据但不推荐这样用)

     delete 类型 用于删除一条数据,对服务器端产生影响

 

     这样,四种请求类型刚好可对应于对数据的 查询,添加,修改,删除。WebApi也推荐如此使用。在WebApi项目中,我们请求的不再是一个具体页面,而是各个控制器中的方法(控制器也是一种类,默认放在Controllers文件夹中)。下面我们将要建立一个ProductController.cs控制器类,其中的方法都是以“Get Post Put Delete”中的任一一个开头的,这样的开头使得Get类型的请求发送给以Get开头的方法去处理,Post类型的请求交给Post开头的方法去处理,Put和Delete同理。

    而以Get开头的方法有好几个也是可以的,此时如何区分到底交给哪个方法执行呢?这就取决于Get开头的方法们的传入参数了,一会儿在代码中可以分辨。
   构建Controller层,在Controllers文件夹中建立一个ProductController.cs控制器类,如下:


   
   
  1. using System;
  2. using System .Collections .Generic;
  3. using System .Linq;
  4. using System .Web;
  5. using System .Web .Mvc;
  6. using ProductStore .Models;
  7. using System .Web .Http;
  8. using System .Net;
  9. using System .Net .Http;
  10. namespace ProductStore .Controllers
  11. {
  12. public class ProductsController : ApiController
  13. {
  14. static readonly IProductRepository repository = new ProductRepository();
  15. // GET: /api/products
  16. public IEnumerable<Product> GetAllProducts()
  17. {
  18. return repository. GetAll();
  19. }
  20. // GET: / api/ products/ id
  21. public Product GetProduct( int id)
  22. {
  23. Product item = repository.Get(id);
  24. if (item == null)
  25. {
  26. throw new HttpResponseException(HttpStatusCode.NotFound);
  27. }
  28. return item;
  29. }
  30. // GET: / api/ products? category= category
  31. public IEnumerable< Product> GetProductsByCategory( string category)
  32. {
  33. return repository.GetAll().Where(p=>string.Equals(p.Category,category,StringComparison.OrdinalIgnoreCase));
  34. }
  35. // POST: / api/ products
  36. public HttpResponseMessage PostProduct( Product item)
  37. {
  38. item = repository.Add(item);
  39. var response = Request.CreateResponse<Product>(HttpStatusCode.Created,item);
  40. string uri = Url.Link("DefaultApi", new { id=item.Id});
  41. response .Headers .Location = new Uri( uri);
  42. return response;
  43. }
  44. // PUT: / api/ products/ id
  45. public void PutProduct( int id, Product product)
  46. {
  47. product.Id = id;
  48. if (!repository.Update(product))
  49. {
  50. throw new HttpResponseException(HttpStatusCode.NotFound);
  51. }
  52. }
  53. // Delete: / api/ products/ id
  54. public void DeleteProduct( int id)
  55. {
  56. Product item = repository.Get(id);
  57. if (item == null)
  58. {
  59. throw new HttpResponseException(HttpStatusCode.NotFound);
  60. }
  61. repository .Remove( id);
  62. }
  63. }
  64. }

使该类继承于ApiController类,在其中实现处理各种Get,Post,Put,Delete类型Http请求的方法。

每一个方法前都有一句注释,标识了该方法的针对的请求的类型(取决于方法的开头),以及要请求到该方法,需要使用的url。

这些url是有规律的,见下图:

Asp.net WebApi 项目示例(增删改查)3

api是必须的,products对应的是ProductsControllers控制器,然后又Http请求的类型和url的后边地址决定。

这里,我们除了第三个“Get a product by category”,其他方法都实现了。

7)最后,我们来构建View视图层,我们更改Views文件夹中的Home文件夹下的Index.cshtml文件,这个文件是项目启动页,如下:


   
   
  1. < div id=" body">
  2. < script src="~/ Scripts/ jquery-1 .8 .2 .min .js"></ script>
  3. < section >
  4.   < h2>添加记录</ h2>
  5.    Name:< input id=" name" type=" text" />< br />
  6.    Category:< input id=" category" type=" text" />
  7.    Price:< input id=" price" type=" text" />< br />
  8.   < input id=" addItem" type=" button" value="添加" />
  9. </ section>
  10. < section>
  11. < br />
  12. < br />
  13.   < h2>修改记录</ h2>
  14.    Id:< input id=" id2" type=" text" />< br />
  15.    Name:< input id=" name2" type=" text" />< br />
  16.    Category:< input id=" category2" type=" text" />
  17.    Price:< input id=" price2" type=" text" />< br />
  18.   < input id=" showItem" type=" button" value="查询" />
  19.   < input id=" editItem" type=" button" value="修改" />
  20.   < input id=" removeItem" type=" button" value="删除" />
  21. </ section>
  22. </ div>

8)然后我们给页面添加js代码,对应上面的按钮事件,用来发起Http请求,如下:


   
   
  1. < script>
  2. //用于保存用户输入数据
  3. var Product = {
  4. create: function () {
  5. Id: "";
  6. Name: "";
  7. Category: "";
  8. Price: "";
  9. return Product;
  10. }
  11. }
  12. //添加一条记录 请求类型 :POST 请求 url: / api/ Products
  13. //请求到 ProductsController .cs中的 public HttpResponseMessage PostProduct( Product item) 方法
  14. $(" #addItem") .click( function () {
  15. var newProduct = Product.create();
  16. newProduct.Name = $("#name").val();
  17. newProduct.Category = $("#category").val();
  18. newProduct.Price = $("#price").val();
  19. $.ajax({
  20. url: "/api/Products",
  21. type: "POST",
  22. contentType: "application/json; charset=utf-8",
  23. data: JSON. stringify(newProduct),
  24. success: function () {
  25. alert( "添加成功!");
  26. },
  27. error: function ( XMLHttpRequest, textStatus, errorThrown) {
  28. alert("请求失败,消息:" + textStatus + " " + errorThrown);
  29. }
  30. });
  31. });
  32. //先根据 Id查询记录 请求类型 :GET 请求 url: / api/ Products/ Id
  33. //请求到 ProductsController .cs中的 public Product GetProduct( int id) 方法
  34. $(" #showItem") .click( function () {
  35. var inputId = $("#id2").val();
  36. $("#name2").val("");
  37. $("#category2").val("");
  38. $("#price2").val("");
  39. $.ajax({
  40. url: "/api/Products/" + inputId,
  41. type: "GET",
  42. contentType: "application/json; charset=urf-8",
  43. success: function (data) {
  44. $( "#name2"). val(data.Name);
  45. $("#category2").val(data.Category);
  46. $("#price2").val(data.Price);
  47. },
  48. error: function ( XMLHttpRequest, textStatus, errorThrown) {
  49. alert("请求失败,消息:" + textStatus + " " + errorThrown);
  50. }
  51. });
  52. });
  53. //修改该 Id的记录 请求类型 :PUT 请求 url: / api/ Products/ Id
  54. //请求到 ProductsController .cs中的 public void PutProduct( int id, Product product) 方法
  55. $(" #editItem") .click( function () {
  56. var inputId = $("#id2").val();
  57. var newProduct = Product.create();
  58. newProduct.Name = $("#name2").val();
  59. newProduct.Category = $("#category2").val();
  60. newProduct.Price = $("#price2").val();
  61. $.ajax({
  62. url: "/api/Products/" + inputId,
  63. type: "PUT",
  64. data: JSON. stringify(newProduct),
  65. contentType: "application/json; charset=urf-8",
  66. success: function () {
  67. alert( "修改成功! ");
  68. },
  69. error: function ( XMLHttpRequest, textStatus, errorThrown) {
  70. alert("请求失败,消息:" + textStatus + " " + errorThrown);
  71. }
  72. });
  73. });
  74. //删除输入 Id的记录 请求类型 :DELETE 请求 url: / api/ Products/ Id
  75. //请求到 ProductsController .cs中的 public void DeleteProduct( int id) 方法
  76. $(" #removeItem") .click( function () {
  77. var inputId = $("#id2").val();
  78. $.ajax({
  79. url: "/api/Products/" + inputId,
  80. type: "DELETE",
  81. contentType: "application/json; charset=uft-8",
  82. success: function (data) {
  83. alert( "Id为 " + inputId + " 的记录删除成功!");
  84. },
  85. error: function ( XMLHttpRequest, textStatus, errorThrown) {
  86. alert("请求失败,消息:" + textStatus + " " + errorThrown);
  87. }
  88. });
  89. });
  90. </ script>

这里,WebApi的一个简单的增删改查项目就完成了,选择执行项目即可测试。注意到,其中用ajax发起请求时,发送到服务器端的数据直接是一个json字符串,当然这个json字符串中每个字段要和Product.cs类中的每个字段同名对应,在服务器端接收数据的时候,我们并没有对接收到的数据进行序列化,而返

1.WebApi是什么

    ASP.NET Web API 是一种框架,用于轻松构建可以由多种客户端(包括浏览器和移动设备)访问的 HTTP 服务。ASP.NET Web API 是一种用于在 .NET Framework 上构建 RESTful 应用程序的理想平台。

    可以把WebApi看成Asp.Net项目类型中的一种,其他项目类型诸如我们熟知的WebForm项目,Windows窗体项目,控制台应用程序等。

    WebApi类型项目的最大优势就是,开发者再也不用担心客户端和服务器之间传输的数据的序列化和反序列化问题,因为WebApi是强类型的,可以自动进行序列化和反序列化,一会儿项目中会见到。

    下面我们建立了一个WebApi类型的项目,项目中对产品Product进行增删改查,Product的数据存放在List<>列表(即内存)中。

2.页面运行效果

Asp.net WebApi 项目示例(增删改查)0

如图所示,可以添加一条记录; 输入记录的Id,查询出该记录的其它信息; 修改该Id的记录; 删除该Id的记录。

3.二话不说,开始建项目

1)新建一个“ASP.NET MVC 4 Web 应用程序”项目,命名为“ProductStore”,点击确定,如图

Asp.net WebApi 项目示例(增删改查)1

2)选择模板“Web API”,点击确定,如图

Asp.net WebApi 项目示例(增删改查)2

3)和MVC类型的项目相似,构建程序的过程是先建立数据模型(Model)用于存取数据, 再建立控制器层(Controller)用于处理发来的Http请求,最后构造显示层(View)用于接收用户的输入和用户进行直接交互。

 

     这里我们先在Models文件夹中建立产品Product类: Product.cs,如下:


   
   
  1. using System;
  2. using System .Collections .Generic;
  3. using System .Linq;
  4. using System .Web;
  5. namespace ProductStore .Models
  6. {
  7. public class Product
  8. {
  9. public int Id { get; set; }
  10. public string Name { get; set; }
  11. public string Category { get; set; }
  12. public decimal Price { get; set; }
  13. }
  14. }

4)试想,我们目前只有一个Product类型的对象,我们要编写一个类对其实现增删改查,以后我们可能会增加其他的类型的对象,再需要编写一个对新类型的对象进行增删改查的类,为了便于拓展和调用,我们在Product之上构造一个接口,使这个接口约定增删改查的方法名称和参数,所以我们在Models文件夹中新建一个接口:  IProductRepository.cs ,如下:


   
   
  1. using System;
  2. using System .Collections .Generic;
  3. using System .Linq;
  4. using System .Text;
  5. using System .Threading .Tasks;
  6. namespace ProductStore .Models
  7. {
  8. interface IProductRepository
  9. {
  10. IEnumerable<Product> GetAll();
  11. Product Get(int id);
  12. Product Add(Product item);
  13. void Remove(int id);
  14. bool Update(Product item);
  15. }
  16. }

5)然后,我们实现这个接口,在Models文件夹中新建一个类,具体针对Product类型的对象进行增删改查存取数据,并在该类的构造方法中,向List<Product>列表中存入几条数据,这个类叫:ProductRepository.cs,如下:


   
   
  1. using System;
  2. using System .Collections .Generic;
  3. using System .Linq;
  4. using System .Web;
  5. namespace ProductStore .Models
  6. {
  7. public class ProductRepository:IProductRepository
  8. {
  9. private List<Product> products = new List<Product>();
  10. private int _nextId = 1;
  11. public ProductRepository()
  12. {
  13. Add(new Product { Name="Tomato soup",Category="Groceries",Price=1.39M});
  14. Add( new Product { Name="Yo-yo",Category="Toys",Price=3.75M});
  15. Add( new Product { Name = "Hammer", Category = "Hardware", Price = 16.99M });
  16. }
  17. public IEnumerable< Product> GetAll()
  18. {
  19. return products;
  20. }
  21. public Product Get( int id)
  22. {
  23. return products.Find(p=>p.Id==id);
  24. }
  25. public Product Add( Product item)
  26. {
  27. if (item == null)
  28. {
  29. throw new ArgumentNullException("item");
  30. }
  31. item .Id = _ nextId++;
  32. products .Add( item);
  33. return item;
  34. }
  35. public void Remove( int id)
  36. {
  37. products.RemoveAll(p=>p.Id==id);
  38. }
  39. public bool Update( Product item)
  40. {
  41. if (item == null)
  42. {
  43. throw new ArgumentNullException("item");
  44. }
  45. int index = products .FindIndex( p=> p .Id== item .Id);
  46. if ( index == -1)
  47. {
  48. return false;
  49. }
  50. products .RemoveAt( index);
  51. products .Add( item);
  52. return true;
  53. }
  54. }
  55. }

此时,Model层就构建好了。

6)下面,我们要构建Controller层,在此之前,先回顾一下Http中几种请求类型,如下

 

     get  类型  用于从服务器端获取数据,且不应该对服务器端有任何操作和影响

     post 类型  用于发送数据到服务器端,创建一条新的数据,对服务器端产生影响

     put 类型  用于向服务器端更新一条数据,对服务器端产生影响 (也可创建一条新的数据但不推荐这样用)

     delete 类型 用于删除一条数据,对服务器端产生影响

 

     这样,四种请求类型刚好可对应于对数据的 查询,添加,修改,删除。WebApi也推荐如此使用。在WebApi项目中,我们请求的不再是一个具体页面,而是各个控制器中的方法(控制器也是一种类,默认放在Controllers文件夹中)。下面我们将要建立一个ProductController.cs控制器类,其中的方法都是以“Get Post Put Delete”中的任一一个开头的,这样的开头使得Get类型的请求发送给以Get开头的方法去处理,Post类型的请求交给Post开头的方法去处理,Put和Delete同理。

    而以Get开头的方法有好几个也是可以的,此时如何区分到底交给哪个方法执行呢?这就取决于Get开头的方法们的传入参数了,一会儿在代码中可以分辨。
   构建Controller层,在Controllers文件夹中建立一个ProductController.cs控制器类,如下:


   
   
  1. using System;
  2. using System .Collections .Generic;
  3. using System .Linq;
  4. using System .Web;
  5. using System .Web .Mvc;
  6. using ProductStore .Models;
  7. using System .Web .Http;
  8. using System .Net;
  9. using System .Net .Http;
  10. namespace ProductStore .Controllers
  11. {
  12. public class ProductsController : ApiController
  13. {
  14. static readonly IProductRepository repository = new ProductRepository();
  15. // GET: /api/products
  16. public IEnumerable<Product> GetAllProducts()
  17. {
  18. return repository. GetAll();
  19. }
  20. // GET: / api/ products/ id
  21. public Product GetProduct( int id)
  22. {
  23. Product item = repository.Get(id);
  24. if (item == null)
  25. {
  26. throw new HttpResponseException(HttpStatusCode.NotFound);
  27. }
  28. return item;
  29. }
  30. // GET: / api/ products? category= category
  31. public IEnumerable< Product> GetProductsByCategory( string category)
  32. {
  33. return repository.GetAll().Where(p=>string.Equals(p.Category,category,StringComparison.OrdinalIgnoreCase));
  34. }
  35. // POST: / api/ products
  36. public HttpResponseMessage PostProduct( Product item)
  37. {
  38. item = repository.Add(item);
  39. var response = Request.CreateResponse<Product>(HttpStatusCode.Created,item);
  40. string uri = Url.Link("DefaultApi", new { id=item.Id});
  41. response .Headers .Location = new Uri( uri);
  42. return response;
  43. }
  44. // PUT: / api/ products/ id
  45. public void PutProduct( int id, Product product)
  46. {
  47. product.Id = id;
  48. if (!repository.Update(product))
  49. {
  50. throw new HttpResponseException(HttpStatusCode.NotFound);
  51. }
  52. }
  53. // Delete: / api/ products/ id
  54. public void DeleteProduct( int id)
  55. {
  56. Product item = repository.Get(id);
  57. if (item == null)
  58. {
  59. throw new HttpResponseException(HttpStatusCode.NotFound);
  60. }
  61. repository .Remove( id);
  62. }
  63. }
  64. }

使该类继承于ApiController类,在其中实现处理各种Get,Post,Put,Delete类型Http请求的方法。

每一个方法前都有一句注释,标识了该方法的针对的请求的类型(取决于方法的开头),以及要请求到该方法,需要使用的url。

这些url是有规律的,见下图:

Asp.net WebApi 项目示例(增删改查)3

api是必须的,products对应的是ProductsControllers控制器,然后又Http请求的类型和url的后边地址决定。

这里,我们除了第三个“Get a product by category”,其他方法都实现了。

7)最后,我们来构建View视图层,我们更改Views文件夹中的Home文件夹下的Index.cshtml文件,这个文件是项目启动页,如下:


   
   
  1. < div id=" body">
  2. < script src="~/ Scripts/ jquery-1 .8 .2 .min .js"></ script>
  3. < section >
  4.   < h2>添加记录</ h2>
  5.    Name:< input id=" name" type=" text" />< br />
  6.    Category:< input id=" category" type=" text" />
  7.    Price:< input id=" price" type=" text" />< br />
  8.   < input id=" addItem" type=" button" value="添加" />
  9. </ section>
  10. < section>
  11. < br />
  12. < br />
  13.   < h2>修改记录</ h2>
  14.    Id:< input id=" id2" type=" text" />< br />
  15.    Name:< input id=" name2" type=" text" />< br />
  16.    Category:< input id=" category2" type=" text" />
  17.    Price:< input id=" price2" type=" text" />< br />
  18.   < input id=" showItem" type=" button" value="查询" />
  19.   < input id=" editItem" type=" button" value="修改" />
  20.   < input id=" removeItem" type=" button" value="删除" />
  21. </ section>
  22. </ div>

8)然后我们给页面添加js代码,对应上面的按钮事件,用来发起Http请求,如下:


   
   
  1. < script>
  2. //用于保存用户输入数据
  3. var Product = {
  4. create: function () {
  5. Id: "";
  6. Name: "";
  7. Category: "";
  8. Price: "";
  9. return Product;
  10. }
  11. }
  12. //添加一条记录 请求类型 :POST 请求 url: / api/ Products
  13. //请求到 ProductsController .cs中的 public HttpResponseMessage PostProduct( Product item) 方法
  14. $(" #addItem") .click( function () {
  15. var newProduct = Product.create();
  16. newProduct.Name = $("#name").val();
  17. newProduct.Category = $("#category").val();
  18. newProduct.Price = $("#price").val();
  19. $.ajax({
  20. url: "/api/Products",
  21. type: "POST",
  22. contentType: "application/json; charset=utf-8",
  23. data: JSON. stringify(newProduct),
  24. success: function () {
  25. alert( "添加成功!");
  26. },
  27. error: function ( XMLHttpRequest, textStatus, errorThrown) {
  28. alert("请求失败,消息:" + textStatus + " " + errorThrown);
  29. }
  30. });
  31. });
  32. //先根据 Id查询记录 请求类型 :GET 请求 url: / api/ Products/ Id
  33. //请求到 ProductsController .cs中的 public Product GetProduct( int id) 方法
  34. $(" #showItem") .click( function () {
  35. var inputId = $("#id2").val();
  36. $("#name2").val("");
  37. $("#category2").val("");
  38. $("#price2").val("");
  39. $.ajax({
  40. url: "/api/Products/" + inputId,
  41. type: "GET",
  42. contentType: "application/json; charset=urf-8",
  43. success: function (data) {
  44. $( "#name2"). val(data.Name);
  45. $("#category2").val(data.Category);
  46. $("#price2").val(data.Price);
  47. },
  48. error: function ( XMLHttpRequest, textStatus, errorThrown) {
  49. alert("请求失败,消息:" + textStatus + " " + errorThrown);
  50. }
  51. });
  52. });
  53. //修改该 Id的记录 请求类型 :PUT 请求 url: / api/ Products/ Id
  54. //请求到 ProductsController .cs中的 public void PutProduct( int id, Product product) 方法
  55. $(" #editItem") .click( function () {
  56. var inputId = $("#id2").val();
  57. var newProduct = Product.create();
  58. newProduct.Name = $("#name2").val();
  59. newProduct.Category = $("#category2").val();
  60. newProduct.Price = $("#price2").val();
  61. $.ajax({
  62. url: "/api/Products/" + inputId,
  63. type: "PUT",
  64. data: JSON. stringify(newProduct),
  65. contentType: "application/json; charset=urf-8",
  66. success: function () {
  67. alert( "修改成功! ");
  68. },
  69. error: function ( XMLHttpRequest, textStatus, errorThrown) {
  70. alert("请求失败,消息:" + textStatus + " " + errorThrown);
  71. }
  72. });
  73. });
  74. //删除输入 Id的记录 请求类型 :DELETE 请求 url: / api/ Products/ Id
  75. //请求到 ProductsController .cs中的 public void DeleteProduct( int id) 方法
  76. $(" #removeItem") .click( function () {
  77. var inputId = $("#id2").val();
  78. $.ajax({
  79. url: "/api/Products/" + inputId,
  80. type: "DELETE",
  81. contentType: "application/json; charset=uft-8",
  82. success: function (data) {
  83. alert( "Id为 " + inputId + " 的记录删除成功!");
  84. },
  85. error: function ( XMLHttpRequest, textStatus, errorThrown) {
  86. alert("请求失败,消息:" + textStatus + " " + errorThrown);
  87. }
  88. });
  89. });
  90. </ script>

这里,WebApi的一个简单的增删改查项目就完成了,选择执行项目即可测试。注意到,其中用ajax发起请求时,发送到服务器端的数据直接是一个json字符串,当然这个json字符串中每个字段要和Product.cs类中的每个字段同名对应,在服务器端接收数据的时候,我们并没有对接收到的数据进行序列化,而返回数据给客户端的时候也并没有对数据进行反序列化,大大节省了以前开发中不停地进行序列化和反序列化的时间。

回数据给客户端的时候也并没有对数据进行反序列化,大大节省了以前开发中不停地进行序列化和反序列化的时间。

1.WebApi是什么

    ASP.NET Web API 是一种框架,用于轻松构建可以由多种客户端(包括浏览器和移动设备)访问的 HTTP 服务。ASP.NET Web API 是一种用于在 .NET Framework 上构建 RESTful 应用程序的理想平台。

    可以把WebApi看成Asp.Net项目类型中的一种,其他项目类型诸如我们熟知的WebForm项目,Windows窗体项目,控制台应用程序等。

    WebApi类型项目的最大优势就是,开发者再也不用担心客户端和服务器之间传输的数据的序列化和反序列化问题,因为WebApi是强类型的,可以自动进行序列化和反序列化,一会儿项目中会见到。

    下面我们建立了一个WebApi类型的项目,项目中对产品Product进行增删改查,Product的数据存放在List<>列表(即内存)中。

2.页面运行效果

Asp.net WebApi 项目示例(增删改查)0

如图所示,可以添加一条记录; 输入记录的Id,查询出该记录的其它信息; 修改该Id的记录; 删除该Id的记录。

3.二话不说,开始建项目

1)新建一个“ASP.NET MVC 4 Web 应用程序”项目,命名为“ProductStore”,点击确定,如图

Asp.net WebApi 项目示例(增删改查)1

2)选择模板“Web API”,点击确定,如图

Asp.net WebApi 项目示例(增删改查)2

3)和MVC类型的项目相似,构建程序的过程是先建立数据模型(Model)用于存取数据, 再建立控制器层(Controller)用于处理发来的Http请求,最后构造显示层(View)用于接收用户的输入和用户进行直接交互。

 

     这里我们先在Models文件夹中建立产品Product类: Product.cs,如下:


   
   
  1. using System;
  2. using System .Collections .Generic;
  3. using System .Linq;
  4. using System .Web;
  5. namespace ProductStore .Models
  6. {
  7. public class Product
  8. {
  9. public int Id { get; set; }
  10. public string Name { get; set; }
  11. public string Category { get; set; }
  12. public decimal Price { get; set; }
  13. }
  14. }

4)试想,我们目前只有一个Product类型的对象,我们要编写一个类对其实现增删改查,以后我们可能会增加其他的类型的对象,再需要编写一个对新类型的对象进行增删改查的类,为了便于拓展和调用,我们在Product之上构造一个接口,使这个接口约定增删改查的方法名称和参数,所以我们在Models文件夹中新建一个接口:  IProductRepository.cs ,如下:


   
   
  1. using System;
  2. using System .Collections .Generic;
  3. using System .Linq;
  4. using System .Text;
  5. using System .Threading .Tasks;
  6. namespace ProductStore .Models
  7. {
  8. interface IProductRepository
  9. {
  10. IEnumerable<Product> GetAll();
  11. Product Get(int id);
  12. Product Add(Product item);
  13. void Remove(int id);
  14. bool Update(Product item);
  15. }
  16. }

5)然后,我们实现这个接口,在Models文件夹中新建一个类,具体针对Product类型的对象进行增删改查存取数据,并在该类的构造方法中,向List<Product>列表中存入几条数据,这个类叫:ProductRepository.cs,如下:


   
   
  1. using System;
  2. using System .Collections .Generic;
  3. using System .Linq;
  4. using System .Web;
  5. namespace ProductStore .Models
  6. {
  7. public class ProductRepository:IProductRepository
  8. {
  9. private List<Product> products = new List<Product>();
  10. private int _nextId = 1;
  11. public ProductRepository()
  12. {
  13. Add(new Product { Name="Tomato soup",Category="Groceries",Price=1.39M});
  14. Add( new Product { Name="Yo-yo",Category="Toys",Price=3.75M});
  15. Add( new Product { Name = "Hammer", Category = "Hardware", Price = 16.99M });
  16. }
  17. public IEnumerable< Product> GetAll()
  18. {
  19. return products;
  20. }
  21. public Product Get( int id)
  22. {
  23. return products.Find(p=>p.Id==id);
  24. }
  25. public Product Add( Product item)
  26. {
  27. if (item == null)
  28. {
  29. throw new ArgumentNullException("item");
  30. }
  31. item .Id = _ nextId++;
  32. products .Add( item);
  33. return item;
  34. }
  35. public void Remove( int id)
  36. {
  37. products.RemoveAll(p=>p.Id==id);
  38. }
  39. public bool Update( Product item)
  40. {
  41. if (item == null)
  42. {
  43. throw new ArgumentNullException("item");
  44. }
  45. int index = products .FindIndex( p=> p .Id== item .Id);
  46. if ( index == -1)
  47. {
  48. return false;
  49. }
  50. products .RemoveAt( index);
  51. products .Add( item);
  52. return true;
  53. }
  54. }
  55. }

此时,Model层就构建好了。

6)下面,我们要构建Controller层,在此之前,先回顾一下Http中几种请求类型,如下

 

     get  类型  用于从服务器端获取数据,且不应该对服务器端有任何操作和影响

     post 类型  用于发送数据到服务器端,创建一条新的数据,对服务器端产生影响

     put 类型  用于向服务器端更新一条数据,对服务器端产生影响 (也可创建一条新的数据但不推荐这样用)

     delete 类型 用于删除一条数据,对服务器端产生影响

 

     这样,四种请求类型刚好可对应于对数据的 查询,添加,修改,删除。WebApi也推荐如此使用。在WebApi项目中,我们请求的不再是一个具体页面,而是各个控制器中的方法(控制器也是一种类,默认放在Controllers文件夹中)。下面我们将要建立一个ProductController.cs控制器类,其中的方法都是以“Get Post Put Delete”中的任一一个开头的,这样的开头使得Get类型的请求发送给以Get开头的方法去处理,Post类型的请求交给Post开头的方法去处理,Put和Delete同理。

    而以Get开头的方法有好几个也是可以的,此时如何区分到底交给哪个方法执行呢?这就取决于Get开头的方法们的传入参数了,一会儿在代码中可以分辨。
   构建Controller层,在Controllers文件夹中建立一个ProductController.cs控制器类,如下:


   
   
  1. using System;
  2. using System .Collections .Generic;
  3. using System .Linq;
  4. using System .Web;
  5. using System .Web .Mvc;
  6. using ProductStore .Models;
  7. using System .Web .Http;
  8. using System .Net;
  9. using System .Net .Http;
  10. namespace ProductStore .Controllers
  11. {
  12. public class ProductsController : ApiController
  13. {
  14. static readonly IProductRepository repository = new ProductRepository();
  15. // GET: /api/products
  16. public IEnumerable<Product> GetAllProducts()
  17. {
  18. return repository. GetAll();
  19. }
  20. // GET: / api/ products/ id
  21. public Product GetProduct( int id)
  22. {
  23. Product item = repository.Get(id);
  24. if (item == null)
  25. {
  26. throw new HttpResponseException(HttpStatusCode.NotFound);
  27. }
  28. return item;
  29. }
  30. // GET: / api/ products? category= category
  31. public IEnumerable< Product> GetProductsByCategory( string category)
  32. {
  33. return repository.GetAll().Where(p=>string.Equals(p.Category,category,StringComparison.OrdinalIgnoreCase));
  34. }
  35. // POST: / api/ products
  36. public HttpResponseMessage PostProduct( Product item)
  37. {
  38. item = repository.Add(item);
  39. var response = Request.CreateResponse<Product>(HttpStatusCode.Created,item);
  40. string uri = Url.Link("DefaultApi", new { id=item.Id});
  41. response .Headers .Location = new Uri( uri);
  42. return response;
  43. }
  44. // PUT: / api/ products/ id
  45. public void PutProduct( int id, Product product)
  46. {
  47. product.Id = id;
  48. if (!repository.Update(product))
  49. {
  50. throw new HttpResponseException(HttpStatusCode.NotFound);
  51. }
  52. }
  53. // Delete: / api/ products/ id
  54. public void DeleteProduct( int id)
  55. {
  56. Product item = repository.Get(id);
  57. if (item == null)
  58. {
  59. throw new HttpResponseException(HttpStatusCode.NotFound);
  60. }
  61. repository .Remove( id);
  62. }
  63. }
  64. }

使该类继承于ApiController类,在其中实现处理各种Get,Post,Put,Delete类型Http请求的方法。

每一个方法前都有一句注释,标识了该方法的针对的请求的类型(取决于方法的开头),以及要请求到该方法,需要使用的url。

这些url是有规律的,见下图:

Asp.net WebApi 项目示例(增删改查)3

api是必须的,products对应的是ProductsControllers控制器,然后又Http请求的类型和url的后边地址决定。

这里,我们除了第三个“Get a product by category”,其他方法都实现了。

7)最后,我们来构建View视图层,我们更改Views文件夹中的Home文件夹下的Index.cshtml文件,这个文件是项目启动页,如下:


   
   
  1. < div id=" body">
  2. < script src="~/ Scripts/ jquery-1 .8 .2 .min .js"></ script>
  3. < section >
  4.   < h2>添加记录</ h2>
  5.    Name:< input id=" name" type=" text" />< br />
  6.    Category:< input id=" category" type=" text" />
  7.    Price:< input id=" price" type=" text" />< br />
  8.   < input id=" addItem" type=" button" value="添加" />
  9. </ section>
  10. < section>
  11. < br />
  12. < br />
  13.   < h2>修改记录</ h2>
  14.    Id:< input id=" id2" type=" text" />< br />
  15.    Name:< input id=" name2" type=" text" />< br />
  16.    Category:< input id=" category2" type=" text" />
  17.    Price:< input id=" price2" type=" text" />< br />
  18.   < input id=" showItem" type=" button" value="查询" />
  19.   < input id=" editItem" type=" button" value="修改" />
  20.   < input id=" removeItem" type=" button" value="删除" />
  21. </ section>
  22. </ div>

8)然后我们给页面添加js代码,对应上面的按钮事件,用来发起Http请求,如下:


   
   
  1. < script>
  2. //用于保存用户输入数据
  3. var Product = {
  4. create: function () {
  5. Id: "";
  6. Name: "";
  7. Category: "";
  8. Price: "";
  9. return Product;
  10. }
  11. }
  12. //添加一条记录 请求类型 :POST 请求 url: / api/ Products
  13. //请求到 ProductsController .cs中的 public HttpResponseMessage PostProduct( Product item) 方法
  14. $(" #addItem") .click( function () {
  15. var newProduct = Product.create();
  16. newProduct.Name = $("#name").val();
  17. newProduct.Category = $("#category").val();
  18. newProduct.Price = $("#price").val();
  19. $.ajax({
  20. url: "/api/Products",
  21. type: "POST",
  22. contentType: "application/json; charset=utf-8",
  23. data: JSON. stringify(newProduct),
  24. success: function () {
  25. alert( "添加成功!");
  26. },
  27. error: function ( XMLHttpRequest, textStatus, errorThrown) {
  28. alert("请求失败,消息:" + textStatus + " " + errorThrown);
  29. }
  30. });
  31. });
  32. //先根据 Id查询记录 请求类型 :GET 请求 url: / api/ Products/ Id
  33. //请求到 ProductsController .cs中的 public Product GetProduct( int id) 方法
  34. $(" #showItem") .click( function () {
  35. var inputId = $("#id2").val();
  36. $("#name2").val("");
  37. $("#category2").val("");
  38. $("#price2").val("");
  39. $.ajax({
  40. url: "/api/Products/" + inputId,
  41. type: "GET",
  42. contentType: "application/json; charset=urf-8",
  43. success: function (data) {
  44. $( "#name2"). val(data.Name);
  45. $("#category2").val(data.Category);
  46. $("#price2").val(data.Price);
  47. },
  48. error: function ( XMLHttpRequest, textStatus, errorThrown) {
  49. alert("请求失败,消息:" + textStatus + " " + errorThrown);
  50. }
  51. });
  52. });
  53. //修改该 Id的记录 请求类型 :PUT 请求 url: / api/ Products/ Id
  54. //请求到 ProductsController .cs中的 public void PutProduct( int id, Product product) 方法
  55. $(" #editItem") .click( function () {
  56. var inputId = $("#id2").val();
  57. var newProduct = Product.create();
  58. newProduct.Name = $("#name2").val();
  59. newProduct.Category = $("#category2").val();
  60. newProduct.Price = $("#price2").val();
  61. $.ajax({
  62. url: "/api/Products/" + inputId,
  63. type: "PUT",
  64. data: JSON. stringify(newProduct),
  65. contentType: "application/json; charset=urf-8",
  66. success: function () {
  67. alert( "修改成功! ");
  68. },
  69. error: function ( XMLHttpRequest, textStatus, errorThrown) {
  70. alert("请求失败,消息:" + textStatus + " " + errorThrown);
  71. }
  72. });
  73. });
  74. //删除输入 Id的记录 请求类型 :DELETE 请求 url: / api/ Products/ Id

猜你喜欢

转载自blog.csdn.net/angel87890/article/details/82979145