$.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); } } });html
[HttpGet] public string GetAllChargingData([FromUri]TB_CHARGING obj) { return "ChargingData" + obj.ID; }
获得结果:前端
若是你不想使用[FromUri]这些在参数里面加特性的这种“怪异”写法,也能够采用先序列化,再在后台反序列的方式。web
$.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; }
这样在后台获得咱们序列化过的对象,再经过反序列化就能获得对象。ajax
通常get请求不建议将数组做为参数,由于咱们知道get请求传递参数的大小是有限制的,最大1024字节,数组里面内容较多时,将其做为参数传递可能会发生参数超限丢失的状况。json
$.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; }
方法名以Get开头,WebApi会自动默认这个请求就是get请求,而若是你以其余名称开头而又不标注方法的请求方式,那么这个时候服务器虽然找到了这个方法,可是因为请求方式不肯定,因此直接返回给你405——方法不被容许的错误。后端
最后结论:全部的WebApi方法最好是加上请求的方式([HttpGet]/[HttpPost]/[HttpPut]/[HttpDelete]),不要偷懒,这样既能防止相似的错误,也有利于方法的维护,别人一看就知道这个方法是什么请求。api
在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; }
这是一种看上去很是正确的写法,但是实际状况是:app
$.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; }
博文的一点评论:
dynamic虽然很巧妙地解决了从请求body中获取参数。可是这样不利于生成api文档。
ps:通常都是用pagehelp等工具,自动读取元数据,生成api文档的。
若是用dynamic的话,生成的文档就只有一个dynamic类型的参数,这样api调用者就没法明确api的参数了。
还有接收参数定义为dynamic类型的话,后续维护或升级太麻烦。
若是是post操做。文中介绍了两种传递实体参数的方法
第一种:
1 |
|
不须要指定contentType。
第二种:
1 |
|
须要指定contentType:"application/json"。两种方式后台均可以获得实体。不知道你的Json字符串是怎么获得的,是拼的字符串?建议使用JSON.stringify( { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" })这种方式获得json字符串。