当前位置: 移动技术网 > IT编程>开发语言>.net > ajax请求基于restFul的WebApi(post、get、delete、put)

ajax请求基于restFul的WebApi(post、get、delete、put)

2018年12月06日  | 移动技术网IT编程  | 我要评论

声讯qb,画神闲,厦门大学校花

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

 

1.何为restful?

restful是符合rest架构风格的网络api接口。

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

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

 

2.restful标准的webapi搭建以及部署在iis上

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

 

 

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

using system;
using system.collections.generic;
using system.data;
using system.data.entity;
using system.data.entity.infrastructure;
using system.linq;
using system.net;
using system.net.http;
using system.web.http;
using system.web.http.description;
using webapi;

namespace webapi.controllers
{
    public class productscontroller : apicontroller
    {
        private dtoolsentities db = new dtoolsentities();

        // get: api/products
        [httpget]
        public iqueryable<product> getproduct()
        {
            return db.product.orderbydescending(p => p.adddate).take(10);
        }

        // get: api/products/5
        [httpget]
        [responsetype(typeof(product))]
        public ihttpactionresult getproduct(int id)
        {
            product product = db.product.find(id);
            if (product == null)
            {
                return notfound();
            }

            return ok(product);
        }

        // put: api/products/5  update 
        [httpput]
        [responsetype(typeof(void))]
        public ihttpactionresult putproduct(int id, product product)
        {
            if (!modelstate.isvalid)
            {
                return badrequest(modelstate);
            }

            if (id != product.id)
            {
                return badrequest();
            }
            product.adddate = datetime.now;
            db.entry(product).state = entitystate.modified;

            try
            {
                db.savechanges();
            }
            catch (dbupdateconcurrencyexception)
            {
                if (!productexists(id))
                {
                    return notfound();
                }
                else
                {
                    throw;
                }
            }

            return statuscode(httpstatuscode.nocontent);
        }


        // post: api/products  
        [httppost]
        [responsetype(typeof(product))]
        public ihttpactionresult postproduct(product product)
        {
            if (!modelstate.isvalid)
            {
                return badrequest(modelstate);
            }
            product.adddate = datetime.now;
            db.product.add(product);
            db.savechanges();

            return createdatroute("defaultapi", new { id = product.id }, product);
        }

        // delete: api/products/5  
        [httpdelete]
        [responsetype(typeof(product))]
        public ihttpactionresult deleteproduct(int id)
        {
            product product = db.product.find(id);
            if (product == null)
            {
                return notfound();
            }

            db.product.remove(product);
            db.savechanges();

            return ok(product);
        }

        protected override void dispose(bool disposing)
        {
            if (disposing)
            {
                db.dispose();
            }
            base.dispose(disposing);
        }

        private bool productexists(int id)
        {
            return db.product.count(e => e.id == id) > 0;
        }
    }
}

 

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

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

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

 

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

<!doctype html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="js/jquery-3.3.1.js"></script>
    <script type="text/javascript">

        //部署在iis上的webapi接口具体请求路径
        var httpurl = "http://192.168.0.142:8018/api/products";

        $(function () {
            $.ajax({
                url: httpurl,
                type: "get",
                datatype: "json",
                success: function (data) {
                    $.each(data, function (index, item) {
                        var tr = $("<tr/>");
                        $("<td/>").html(item["productname"]).appendto(tr);
                        $("<td/>").html(item["brand"]).appendto(tr);
                        $("<td/>").html(item["asin"]).appendto(tr);
                        $("<td/>").html(item["sku"]).appendto(tr);
                        $("<button id ='d' onclick='del(" + item["id"] + ")'>").html("删除").appendto(tr);
                        $("<button id ='u' onclick='update(" + item["id"] + ")'>").html("更新").appendto(tr);
                        tr.appendto("#tab");
                    });
                },
                error: function (xmlhttprequest, textstatus, errorthrown) {
                    alert(xmlhttprequest + "," + textstatus + "," + errorthrown);
                }
            });

        });

        //修改
        function update(id) {
            $.ajax({
                url: httpurl + "?id=" + id,
                type: "put",
                data: { "id": id, "productname": '男士领带', "brand": '海澜之家', "asin": 'sad498ae1', "sku": '98da7e9qe-sdae', "storename": '海澜之家京东自营店' },
                datatype: "json",
                success: function (data) {
                    location.reload();
                }
            })
        }

        //新增
        function add() {
            $.ajax({
                url: httpurl,
                type: "post",
                data: { "productguid": newguid(), "productname": '男士衬衫', "brand": '海澜之家', "asin": 'sad498ae1', "sku": '98da7e9qe-sdae', "storename": '海澜之家天猫旗舰店' },
                datatype: "json",
                success: function (data) {
                    location.reload();
                }
            })
        }

        //删除
        function del(id) {
            $.ajax({
                url: httpurl+"/" + id,
                type: "delete",
                datatype: "json",
                success: function (data) {
                    location.reload();
                }
            });
        }

        //生成guid
        function newguid() {
            var guid = "";
            for (var i = 1; i <= 32; i++) {
                var n = math.floor(math.random() * 16.0).tostring(16);
                guid += n;
                if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
                    guid += "-";
            }
            return guid;
        }
    </script>
</head>
<body>
    <div>
        <table id="tab">
            <tr>
                <th>产品名称</th>
                <th>产品品牌</th>
                <th>asin</th>
                <th>sku</th>
            </tr>
        </table>
        <button id="add" onclick="add()">add</button>
    </div>

</body>
</html>

 

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

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

  问题介绍及原因分析:

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

        解决方案:

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

 

<system.webserver>
    <httpprotocol>
      <customheaders>
        <!--服务器端返回response header  后接url或*  表示允许-->
        <add name="access-control-allow-origin" value="*" />
        <add name="access-control-allow-headers" value="content-type" />
     <!--支持请求的类型--> <add name="access-control-allow-methods" value="get, post, put, delete, options" /> </customheaders> </httpprotocol> <handlers> <remove name="extensionlessurlhandler-integrated-4.0" /> <add name="extensionlessurlhandler-integrated-4.0" path="*." verb="*" type="system.web.handlers.transferrequesthandler" precondition="integratedmode,runtimeversionv4.0" /> </handlers> </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

 <system.webserver>
    <!--以下配置为了让iis 7+支持put/delete方法-->
    <httpprotocol>
      <customheaders>
        <!--服务器端返回response header  后接url或*  表示允许-->
        <add name="access-control-allow-origin" value="*" />
        <add name="access-control-allow-headers" value="content-type" />
        <add name="access-control-allow-methods" value="get, post, put, delete, options" />
      </customheaders>
    </httpprotocol>
    <validation validateintegratedmodeconfiguration="false"/>
    <handlers>
      <!--移除webdav协议-->
      <remove name="webdav"/>
      <remove name="extensionlessurlhandler-integrated-4.0" />
      <!--支持所有方式的请求-->
      <add name="extensionlessurlhandler-integrated-4.0" path="*." verb="*" type="system.web.handlers.transferrequesthandler" precondition="integratedmode,runtimeversionv4.0" />
    </handlers>
    <!--iis7/7.5上必须加这个配置,否则访问报错-->
    <modules  runallmanagedmodulesforallrequests="true">
      <!--移除webdav协议-->
      <remove name="webdavmodule"/>
      <remove name="telemetrycorrelationhttpmodule" />
      <add name="telemetrycorrelationhttpmodule" type="microsoft.aspnet.telemetrycorrelation.telemetrycorrelationhttpmodule, microsoft.aspnet.telemetrycorrelation" precondition="integratedmode,managedhandler" />
    </modules>
  </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添加以下方法就行了

using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.http;
using system.web.mvc;
using system.web.optimization;
using system.web.routing;

namespace webapi
{
    public class webapiapplication : system.web.httpapplication
    {
        protected void application_start()
        {
            arearegistration.registerallareas();
            globalconfiguration.configure(webapiconfig.register);
            filterconfig.registerglobalfilters(globalfilters.filters);
            routeconfig.registerroutes(routetable.routes);
            bundleconfig.registerbundles(bundletable.bundles);
        }

        protected void application_beginrequest()
        {
            if (request.headers.allkeys.contains("origin") && request.httpmethod == "options")
            {
                response.end();
            }
        }
    }
}

 

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

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

 

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网