经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C# » 查看文章
ajax请求基于restFul的WebApi(post、get、delete、put)
来源:cnblogs  作者:生活不止编程  时间:2018/12/7 9:38:10  对本文有异议

近日逛招聘软件,看到部分企业都要会编写、请求restFul的webapi。正巧这段时间较为清闲,于是乎打开vs准备开撸。

 

1.何为restFul?

restFul是符合rest架构风格的网络API接口。

rest是一种软件架构的编码风格,是根据网络应用而去设计和开发的一种可以降低开发复杂度的编码方式,并且可以提高程序的可伸缩性(增减问题)。

几种较为常见的操作类型:get(查询)、post(新增)、put(修改)、delete(删除)

 

2.restFul标准的WebApi搭建以及部署在iis上

在这里为了方便,使用的ef框架,在创建读/写控制器时直接引用了模型类

 

 

控制器直接帮我帮crud的方法都写好了,按照注释的请求规则,可直接使用。代码如下:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Data.Entity;
  5. using System.Data.Entity.Infrastructure;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Http;
  9. using System.Web.Http;
  10. using System.Web.Http.Description;
  11. using webapi;
  12. namespace webapi.Controllers
  13. {
  14. public class ProductsController : ApiController
  15. {
  16. private DtoolsEntities db = new DtoolsEntities();
  17. // GET: api/Products
  18. [HttpGet]
  19. public IQueryable<Product> GetProduct()
  20. {
  21. return db.Product.OrderByDescending(p => p.AddDate).Take(10);
  22. }
  23. // GET: api/Products/5
  24. [HttpGet]
  25. [ResponseType(typeof(Product))]
  26. public IHttpActionResult GetProduct(int id)
  27. {
  28. Product product = db.Product.Find(id);
  29. if (product == null)
  30. {
  31. return NotFound();
  32. }
  33. return Ok(product);
  34. }
  35. // PUT: api/Products/5 update
  36. [HttpPut]
  37. [ResponseType(typeof(void))]
  38. public IHttpActionResult PutProduct(int id, Product product)
  39. {
  40. if (!ModelState.IsValid)
  41. {
  42. return BadRequest(ModelState);
  43. }
  44. if (id != product.Id)
  45. {
  46. return BadRequest();
  47. }
  48. product.AddDate = DateTime.Now;
  49. db.Entry(product).State = EntityState.Modified;
  50. try
  51. {
  52. db.SaveChanges();
  53. }
  54. catch (DbUpdateConcurrencyException)
  55. {
  56. if (!ProductExists(id))
  57. {
  58. return NotFound();
  59. }
  60. else
  61. {
  62. throw;
  63. }
  64. }
  65. return StatusCode(HttpStatusCode.NoContent);
  66. }
  67. // POST: api/Products
  68. [HttpPost]
  69. [ResponseType(typeof(Product))]
  70. public IHttpActionResult PostProduct(Product product)
  71. {
  72. if (!ModelState.IsValid)
  73. {
  74. return BadRequest(ModelState);
  75. }
  76. product.AddDate = DateTime.Now;
  77. db.Product.Add(product);
  78. db.SaveChanges();
  79. return CreatedAtRoute("DefaultApi", new { id = product.Id }, product);
  80. }
  81. // DELETE: api/Products/5
  82. [HttpDelete]
  83. [ResponseType(typeof(Product))]
  84. public IHttpActionResult DeleteProduct(int id)
  85. {
  86. Product product = db.Product.Find(id);
  87. if (product == null)
  88. {
  89. return NotFound();
  90. }
  91. db.Product.Remove(product);
  92. db.SaveChanges();
  93. return Ok(product);
  94. }
  95. protected override void Dispose(bool disposing)
  96. {
  97. if (disposing)
  98. {
  99. db.Dispose();
  100. }
  101. base.Dispose(disposing);
  102. }
  103. private bool ProductExists(int id)
  104. {
  105. return db.Product.Count(e => e.Id == id) > 0;
  106. }
  107. }
  108. }

 

每个控制器前根据类型最好指定[HttpGet]  [HttpPost]   [HttpPut]  [HttpDelete],因为服务器是根据请求类型自动映射匹配控制器名称,加上特性,避免出错。

weiapi设置中指定json格式,避免数据类型异常

webapi的搭建基本没有问题了。接下来就是部署在iis上,这里不多做描述,不懂如何部署iis可点击这里 (会被揍吗?)

 

3.前台ajax请求页面的编写

  1. <!DOCTYPE html>
  2.  
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  6. <title></title>
  7. <script src="js/jquery-3.3.1.js"></script>
  8. <script type="text/javascript">
  9.  
  10. //部署在iis上的webapi接口具体请求路径
  11. var httpUrl = "http://192.168.0.142:8018/api/Products";
  12. $(function () {
  13. $.ajax({
  14. url: httpUrl,
  15. type: "GET",
  16. dataType: "json",
  17. success: function (data) {
  18. $.each(data, function (index, item) {
  19. var tr = $("<tr/>");
  20. $("<td/>").html(item["ProductName"]).appendTo(tr);
  21. $("<td/>").html(item["Brand"]).appendTo(tr);
  22. $("<td/>").html(item["ASIN"]).appendTo(tr);
  23. $("<td/>").html(item["SKU"]).appendTo(tr);
  24. $("<button id ='d' onclick='del(" + item["Id"] + ")'>").html("删除").appendTo(tr);
  25. $("<button id ='u' onclick='update(" + item["Id"] + ")'>").html("更新").appendTo(tr);
  26. tr.appendTo("#tab");
  27. });
  28. },
  29. error: function (XMLHttpRequest, textStatus, errorThrown) {
  30. alert(XMLHttpRequest + "," + textStatus + "," + errorThrown);
  31. }
  32. });
  33. });
  34. //修改
  35. function update(id) {
  36. $.ajax({
  37. url: httpUrl + "?id=" + id,
  38. type: "Put",
  39. data: { "id": id, "ProductName": '男士领带', "Brand": '海澜之家', "ASIN": 'SAD498AE1', "SKU": '98DA7E9QE-SDAE', "StoreName": '海澜之家京东自营店' },
  40. dataType: "json",
  41. success: function (data) {
  42. location.reload();
  43. }
  44. })
  45. }
  46. //新增
  47. function add() {
  48. $.ajax({
  49. url: httpUrl,
  50. type: "Post",
  51. data: { "ProductGuid": newGuid(), "ProductName": '男士衬衫', "Brand": '海澜之家', "ASIN": 'SAD498AE1', "SKU": '98DA7E9QE-SDAE', "StoreName": '海澜之家天猫旗舰店' },
  52. dataType: "json",
  53. success: function (data) {
  54. location.reload();
  55. }
  56. })
  57. }
  58. //删除
  59. function del(id) {
  60. $.ajax({
  61. url: httpUrl+"/" + id,
  62. type: "Delete",
  63. dataType: "json",
  64. success: function (data) {
  65. location.reload();
  66. }
  67. });
  68. }
  69. //生成guid
  70. function newGuid() {
  71. var guid = "";
  72. for (var i = 1; i <= 32; i++) {
  73. var n = Math.floor(Math.random() * 16.0).toString(16);
  74. guid += n;
  75. if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
  76. guid += "-";
  77. }
  78. return guid;
  79. }
  80. </script>
  81. </head>
  82. <body>
  83. <div>
  84. <table id="tab">
  85. <tr>
  86. <th>产品名称</th>
  87. <th>产品品牌</th>
  88. <th>ASIN</th>
  89. <th>SKU</th>
  90. </tr>
  91. </table>
  92. <button id="add" onclick="add()">add</button>
  93. </div>
  94.  
  95. </body>
  96. </html>

 

前端,后端代码都写完了。只剩测试了。想都不用想肯定会出问题的,因为涉及到了跨域请求等,接下来就为大家解决问题。

问题一:ajax请求,涉及到cors跨域,请求失败

  问题介绍及原因分析:

           CORS是一个W3C标准,全称是”跨域资源共享”。它允许浏览器向跨源服务器,发出XMLHttpRequest请求,基本上目前所有的浏览器都实现了CORS标准,其实目前几乎所有的浏览器ajax请求都是基于CORS机制的。
         跨域问题一般发生在Javascript发起AJAX调用,因为浏览器对于这种请求,所给予的权限是较低的,通常只允许调用本域中的资源,除非目标服务器明确地告知它允许跨域调用。所以,跨域的问题虽然是由浏览器的行为产生出来的,但解决的方法却            是在服务端。因为不可能要求所有客户端降低安全性。

        解决方案:

                           web.config修改配置文件,使服务端支持跨域请求

 

  1. <system.webServer>
  2. <httpProtocol>
  3. <customHeaders>
  4. <!--服务器端返回Response header 后接URL或* 表示允许-->
  5. <add name="Access-Control-Allow-Origin" value="*" />
  6. <add name="Access-Control-Allow-Headers" value="Content-Type" />
         <!--支持请求的类型-->
  7. <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  8. </customHeaders>
  9. </httpProtocol>
  10. <handlers>
  11. <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  12. <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  13. </handlers>
  14. </system.webServer>

 

 

问题二:get、post 可正常请求,put、delete 出现405(Method Not Allowed)  注意:我提交Put的请求,浏览器响应的是Request Method:PUT

  问题介绍及原因分析:

           有些人会问:我刚刚在服务端设置了允许put delete请求了,浏览器上服务端的响应也看到了支持put delete,为啥服务端还是拒绝呢?

           一切都是iis的WebDAV(Web Distribution Authorization Versioning) Publish惹的祸,WebDAV是基于HTTP协议的拓展,添加了很多Method用于管理服务器上的文件。若安装了WebDAV,那么iis所有的site都会默认使用WebDAV Module与WebDAV Handler。

          WebDAV Handler的默认配置是处理如下 Method:PROPFIND,PROPPATCH,MKCOL,PUT,COPY,DELETE,MOVE,LOCK,UNLOCK。所以浏览器发送的put delete请求都会被拦截并交给WebDAV Handler来处理,并且WebDAV Handler会默认拒绝请求

        解决方案:

        既然我们找到了问题所在点,那么解决方案应然而生,那就是在配置文件里移除ebDAVModule和WebDAVHandler或者在系统中直接移除WebDAV

  1. <system.webServer>
  2. <!--以下配置为了让IIS 7+支持Put/Delete方法-->
  3. <httpProtocol>
  4. <customHeaders>
  5. <!--服务器端返回Response header 后接URL或* 表示允许-->
  6. <add name="Access-Control-Allow-Origin" value="*" />
  7. <add name="Access-Control-Allow-Headers" value="Content-Type" />
  8. <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  9. </customHeaders>
  10. </httpProtocol>
  11. <validation validateIntegratedModeConfiguration="false"/>
  12. <handlers>
  13. <!--移除WebDAV协议-->
  14. <remove name="WebDAV"/>
  15. <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  16. <!--支持所有方式的请求-->
  17. <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  18. </handlers>
  19. <!--IIS7/7.5上必须加这个配置,否则访问报错-->
  20. <modules runAllManagedModulesForAllRequests="true">
  21. <!--移除WebDAV协议-->
  22. <remove name="WebDAVModule"/>
  23. <remove name="TelemetryCorrelationHttpModule" />
  24. <add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" preCondition="integratedMode,managedHandler" />
  25. </modules>
  26. </system.webServer>

 

问题三:put delete请求,又出现了405(Method Not Allowed)

  问题介绍及原因分析:

           大家发现没有,问题二put提交,Request Method就是put,Delete提交,Request Method就是Delete。然而在这里统统都是OPTIONS。那么这个OPTIONS到底是个啥呢?

           Preflighted Requests(预检请求)
           Preflighted Requests是CORS中一种透明服务器验证机制。预检请求首先需要向另外一个域名的资源发送一个 HTTP OPTIONS 请求头,其目的就是为了判断实际发送的请求是否是安全的
          下面的2种情况需要进行预检:
          1、简单请求,比如使用Content-Type 为 application/xml 或 text/xml 的 POST 请求;
          2、请求中设置自定义头,比如 X-JSON、X-MENGXIANHUI 等。

          原来put、delete请求如果头部设置了XMLHttpRequest.setRequestHeader("Content-Type", "application/json")之前还发送了一次预检请求。

        解决方案:

          既然是多的一次请求,那我们就在服务端过滤掉就好了。

          Global.asac添加以下方法就行了

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Http;
  6. using System.Web.Mvc;
  7. using System.Web.Optimization;
  8. using System.Web.Routing;
  9. namespace webapi
  10. {
  11. public class WebApiApplication : System.Web.HttpApplication
  12. {
  13. protected void Application_Start()
  14. {
  15. AreaRegistration.RegisterAllAreas();
  16. GlobalConfiguration.Configure(WebApiConfig.Register);
  17. FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
  18. RouteConfig.RegisterRoutes(RouteTable.Routes);
  19. BundleConfig.RegisterBundles(BundleTable.Bundles);
  20. }
  21. protected void Application_BeginRequest()
  22. {
  23. if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
  24. {
  25. Response.End();
  26. }
  27. }
  28. }
  29. }

 

到这里,ajax跨域实现RestFul请求,已经是能正常运行了。剩下的只是安全校验、身份认证、异常记录等,就能放到生产环境了。这里就不多做描述了,毕竟博主还是上班族...

如有错误,欢迎大家指正~

 

 

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号