本文转自:http://www.cnblogs.com/landeanfen/p/5337072.html?spm=a2c4e.11153940.blogcont368416.31.79ec4f09ZLRVABhtml
本篇打算经过get、post、put、delete四种请求方式分别谈谈基础类型(包括int/string/datetime等)、实体、数组等类型的参数如何传递。前端
对于取数据,咱们使用最多的应该就是get请求了吧。下面经过几个示例看看咱们的get请求参数传递。web
[HttpGet] public string GetAllChargingData(int id, string name) { return "ChargingData" + id; }
$.ajax({ type: "get", url: "http://localhost:27221/api/Charging/GetAllChargingData", data: { id: 1, name: "Jim", bir: "1988-09-11"}, success: function (data, status) { if (status == "success") { $("#div_test").html(data); } } });
参数截图效果面试
这是get请求最基础的参数传递方式,没什么特别好说的。ajax
若是咱们在get请求时想将实体对象作参数直接传递到后台,是否可行呢?咱们来看看。json
public class TB_CHARGING { /// <summary> /// 主键Id /// </summary> public string ID { get; set; } /// <summary> /// 充电设备名称 /// </summary> public string NAME { get; set; } /// <summary> /// 充电设备描述 /// </summary> public string DES { get; set; } /// <summary> /// 建立时间 /// </summary> public DateTime CREATETIME { get; set; } }
[HttpGet] public string GetByModel(TB_CHARGING oData) { return "ChargingData" + oData.ID; }
$.ajax({ type: "get", url: "http://localhost:27221/api/Charging/GetByModel", contentType: "application/json", data: { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" }, success: function (data, status) { if (status == "success") { $("#div_test").html(data); } } });
测试结果后端
由上图可知,在get请求时,咱们直接将json对象当作实体传递后台,后台是接收不到的。这是为何呢?咱们来看看对应的http请求api
原来,get请求的时候,默认是将参数所有放到了url里面直接以string的形式传递的,后台天然接不到了。数组
缘由分析:还记得有面试题问过get和post请求的区别吗?其中有一个区别就是get请求的数据会附在URL以后(就是把数据放置在HTTP协议头中),而post请求则是放在http协议包的包体中。浏览器
根据园友们的提议,Get请求的时候能够在参数里面加上[FromUri]便可直接获得对象。仍是贴上代码:
var postdata = { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" }; $.ajax({ type: "get", url: "http://localhost:27221/api/Charging/GetAllChargingData", data: postdata, success: function (data, status) { } });
[HttpGet] public string GetAllChargingData([FromUri]TB_CHARGING obj) { return "ChargingData" + obj.ID; }
获得结果:
若是你不想使用[FromUri]这些在参数里面加特性的这种“怪异”写法,也能够采用先序列化,再在后台反序列的方式。
$.ajax({ type: "get", url: "http://localhost:27221/api/Charging/GetByModel", contentType: "application/json", data: { strQuery: JSON.stringify({ ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" }) }, success: function (data, status) { if (status == "success") { $("#div_test").html(data); } } });
[HttpGet] public string GetByModel(string strQuery) { TB_CHARGING oData = Newtonsoft.Json.JsonConvert.DeserializeObject<TB_CHARGING>(strQuery); return "ChargingData" + oData.ID; }
这样在后台获得咱们序列化过的对象,再经过反序列化就能获得对象。
在url里面咱们能够看到它自动给对象加了一个编码:
至于还有园友们提到http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api的model binder这种方式,博主看了下,以为略复杂。有兴趣的也能够试试。至于用哪种方式传递对象,园友们能够自行选择。
通常get请求不建议将数组做为参数,由于咱们知道get请求传递参数的大小是有限制的,最大1024字节,数组里面内容较多时,将其做为参数传递可能会发生参数超限丢失的状况。
为何会说get请求“怪异”呢?咱们先来看看下面的两种写法对比。
$.ajax({ type: "get", url: "http://localhost:27221/api/Charging/GetByModel", contentType: "application/json", data: { strQuery: JSON.stringify({ ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" }) }, success: function (data, status) { if (status == "success") { $("#div_test").html(data); } } });
[HttpGet] public string GetByModel(string strQuery) { TB_CHARGING oData = Newtonsoft.Json.JsonConvert.DeserializeObject<TB_CHARGING>(strQuery); return "ChargingData" + oData.ID; }
这是标准写法,后台加[HttpGet],参数正常获得:
为了对比,我将[HttpGet]去掉,而后再调用
//[HttpGet] public string GetByModel(string strQuery) { TB_CHARGING oData = Newtonsoft.Json.JsonConvert.DeserializeObject<TB_CHARGING>(strQuery); return "ChargingData" + oData.ID; }
貌似没有任何问题!有人就想,那是否全部的get请求均可以省略掉[HttpGet]这个标注呢。咱们试试便知。
咱们把以前的方法名由GetByModel改为FindByModel,这个再正常不过了,不少人查询就不想用Get开头,还有直接用Query开头的。这个有什么关系吗?有没有关系,咱们以事实说话。
$.ajax({ type: "get", url: "http://localhost:27221/api/Charging/FindByModel", contentType: "application/json", data: { strQuery: JSON.stringify({ ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" }) }, success: function (data, status) { if (status == "success") { $("#div_test").html(data); } } });
[HttpGet] public string FindByModel(string strQuery) { TB_CHARGING oData = Newtonsoft.Json.JsonConvert.DeserializeObject<TB_CHARGING>(strQuery); return "ChargingData" + oData.ID; }
貌似又可行,没有任何问题啊。根据上面的推论,咱们去掉[HttpGet]也是可行的,好,咱们注释掉[HttpGet],运行起来试试。
结果是不进断点,有些人不信,咱们在浏览器里面看看http请求:
呵呵,这就奇怪了,就改了个方法名,至于这样么?还真至于!
博主的理解是:方法名以Get开头,WebApi会自动默认这个请求就是get请求,而若是你以其余名称开头而又不标注方法的请求方式,那么这个时候服务器虽然找到了这个方法,可是因为请求方式不肯定,因此直接返回给你405——方法不被容许的错误。
最后结论:全部的WebApi方法最好是加上请求的方式([HttpGet]/[HttpPost]/[HttpPut]/[HttpDelete]),不要偷懒,这样既能防止相似的错误,也有利于方法的维护,别人一看就知道这个方法是什么请求。
这也就是为何不少人在园子里面问道为何方法名不加[HttpGet]就调用不到的缘由!
在WebApi的RESETful风格里面,API服务的增删改查,分别对应着http的post/delete/put/get请求。咱们下面就来讲说post请求参数的传递方式。
post请求的基础类型的参数和get请求有点不同,咱们知道get请求的参数是经过url来传递的,而post请求则是经过http的请求体中传过来的,WebApi的post请求也须要从http的请求体里面去取参数。
$.ajax({ type: "post", url: "http://localhost:27221/api/Charging/SaveData", data: { NAME: "Jim" }, success: function (data, status) { if (status == "success") { $("#div_test").html(data); } } });
[HttpPost] public bool SaveData(string NAME) { return true; }
这是一种看上去很是正确的写法,但是实际状况是:
$.ajax({ type: "post", url: "http://localhost:27221/api/Charging/SaveData", data: { "": "Jim" }, success: function (data, status) {} });
[HttpPost] public bool SaveData([FromBody]string NAME) { return true; }
这是一种另许多人头痛的写法,可是没办法,这样确实能获得咱们的结果:
咱们通常的经过url取参数的机制是键值对,即某一个key等于某一个value,而这里的FromBody和咱们通常经过url取参数的机制则不一样,它的机制是=value,没有key的概念,而且若是你写了key(好比你的ajax参数写的{NAME:"Jim"}),后台反而获得的NAME等于null。不信你能够试试。
上面讲的都是传递一个基础类型参数的状况,那么若是咱们须要传递多个基础类型呢?按照上面的推论,是否能够([FromBody]string NAME, [FromBody]string DES)这样写呢。试试便知。
$.ajax({ type: "post", url: "http://localhost:27221/api/Charging/SaveData", data: { "": "Jim","":"备注" }, success: function (data, status) {} });
[HttpPost] public bool SaveData([FromBody]string NAME, [FromBody] string DES) { return true; }
获得结果
这说明咱们没办法经过多个[FromBody]里面取值,此法失败。
既然上面的办法行不通,那咱们如何传递多个基础类型的数据呢?不少的解决办法是新建一个类去包含传递的参数,博主以为这样不够灵活,由于若是咱们先后台每次传递多个参数的post请求都去新建一个类的话,咱们系统到时候会有多少个这种参数类?维护起来那是至关的麻烦的一件事!因此博主以为使用dynamic是一个很不错的选择。咱们来试试。
$.ajax({ type: "post", url: "http://localhost:27221/api/Charging/SaveData", contentType: 'application/json', data: JSON.stringify({ NAME: "Jim",DES:"备注" }), success: function (data, status) {} });
[HttpPost] public object SaveData(dynamic obj) { var strName = Convert.ToString(obj.NAME); return strName; }
经过dynamic动态类型能顺利获得多个参数,省掉了[FromBody]这个累赘,而且ajax参数的传递不用使用"无厘头"的{"":"value"}这种写法,有没有一种小清新的感受~~有一点须要注意的是这里在ajax的请求里面须要加上参数类型为Json,即 contentType: 'application/json', 这个属性。
经过上文post请求基础类型参数的传递,咱们了解到了dynamic的方便之处,为了不[FromBody]这个累赘和{"":"value"}这种"无厘头"的写法。博主推荐全部基础类型使用dynamic来传递,方便解决了基础类型一个或多个参数的传递,示例如上文。若是园友们有更好的办法,欢迎讨论。
上面咱们经过dynamic类型解决了post请求基础类型数据的传递问题,那么当咱们须要传递一个实体做为参数该怎么解决呢?咱们来看下面的代码便知:
$.ajax({ type: "post", url: "http://localhost:27221/api/Charging/SaveData", data: { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" }, success: function (data, status) {} });
[HttpPost] public bool SaveData(TB_CHARGING oData) { return true; }
获得结果
原理解释:使用实体做为参数的时候,前端直接传递普通json,后台直接使用对应的类型去接收便可,不用FromBody。可是这里须要注意的一点就是,这里不能指定contentType为appplication/json,不然,参数没法传递到后台。咱们来看看它默认的contentType是什么:
为了弄清楚缘由,博主查了下http的Content-Type的类型。看到以下说明:
也就是说post请求默认是将表单里面的数据的key/value形式发送到服务,而咱们的服务器只须要有对应的key/value属性值的对象就能够接收到。而若是使用application/json,则表示将前端的数据以序列化过的json传递到后端,后端要把它变成实体对象,还须要一个反序列化的过程。按照这个逻辑,那咱们若是指定contentType为application/json,而后传递序列化过的对象应该也是能够的啊。博主好奇心重,仍是打算一试到底,因而就有了下面的代码:
var postdata = { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" }; $.ajax({ type: "post", url: "http://localhost:27221/api/Charging/SaveData", contentType: 'application/json', data: JSON.stringify(postdata), success: function (data, status) {} });
[HttpPost] public bool SaveData(TB_CHARGING lstCharging) { return true; }
获得结果:
尝试成功,也就是说,两种写法都是可行的。若是你指定了contentType为application/json,则必需要传递序列化过的对象;若是使用post请求的默认参数类型,则前端直接传递json类型的对象便可。
有些时候,咱们须要将基础类型和实体一块儿传递到后台,这个时候,咱们神奇的dynamic又派上用场了。
var postdata = { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" }; $.ajax({ type: "post", url: "http://localhost:27221/api/Charging/SaveData", contentType: 'application/json', data: JSON.stringify({ NAME:"Lilei", Charging:postdata }), success: function (data, status) {} });
[HttpPost] public object SaveData(dynamic obj) { var strName = Convert.ToString(obj.NAME); var oCharging = Newtonsoft.Json.JsonConvert.DeserializeObject<TB_CHARGING>(Convert.ToString(obj.Charging)); return strName; }
获得结果:
原理也不用多说,同上。
var arr = ["1", "2", "3", "4"]; $.ajax({ type: "post", url: "http://localhost:27221/api/Charging/SaveData", contentType: 'application/json', data: JSON.stringify(arr), success: function (data, status) { } });
[HttpPost] public bool SaveData(string[] ids) { return true; }
获得结果:
var arr = [ { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" }, { ID: "2", NAME: "Lilei", CREATETIME: "1990-12-11" }, { ID: "3", NAME: "Lucy", CREATETIME: "1986-01-10" } ]; $.ajax({ type: "post", url: "http://localhost:27221/api/Charging/SaveData", contentType: 'application/json', data: JSON.stringify(arr), success: function (data, status) {} });
[HttpPost] public bool SaveData(List<TB_CHARGING> lstCharging) { return true; }
获得结果:
上面写了那么多,都是经过前端的ajax请求去作的,咱们知道,若是调用方不是web项目,好比Android客户端,可能须要从后台发送http请求来调用咱们的接口方法,若是咱们经过后台去发送请求是否也是可行的呢?咱们以实体对象做为参数来传递写写代码试一把。
public void TestReques() { //请求路径 string url = "http://localhost:27221/api/Charging/SaveData"; //定义request并设置request的路径 WebRequest request = WebRequest.Create(url); request.Method = "post"; //初始化request参数 string postData = "{ ID: \"1\", NAME: \"Jim\", CREATETIME: \"1988-09-11\" }"; //设置参数的编码格式,解决中文乱码 byte[] byteArray = Encoding.UTF8.GetBytes(postData); //设置request的MIME类型及内容长度 request.ContentType = "application/json"; request.ContentLength = byteArray.Length; //打开request字符流 Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); //定义response为前面的request响应 WebResponse response = request.GetResponse(); //获取相应的状态代码 Console.WriteLine(((HttpWebResponse)response).StatusDescription); //定义response字符流 dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd();//读取全部 Console.WriteLine(responseFromServer); }
当代码运行到request.GetResponse()这一句的时候,API里面进入断点
尝试成功。
WebApi里面put请求通常用于对象的更新。它和用法和post请求基本相同。一样支持[FromBody],一样可使用dynamic。
$.ajax({ type: "put", url: "http://localhost:27221/api/Charging/Update", contentType: 'application/json', data: JSON.stringify({ ID: "1" }), success: function (data, status) {} });
[HttpPut] public bool Update(dynamic obj ) { return true; }
和post请求相同。
和post请求相同。
顾名思义,delete请求确定是用于删除操做的。参数传递机制和post也是基本相同。下面简单给出一个例子,其余状况参考post请求。
var arr = [ { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" }, { ID: "2", NAME: "Lilei", CREATETIME: "1990-12-11" }, { ID: "3", NAME: "Lucy", CREATETIME: "1986-01-10" } ]; $.ajax({ type: "delete", url: "http://localhost:27221/api/Charging/OptDelete", contentType: 'application/json', data: JSON.stringify(arr), success: function (data, status) {} });
[HttpDelete] public bool OptDelete(List<TB_CHARGING> lstChargin) { return true; }