一、get请求
对于取数据,我们使用最多的应该就是get请求了吧。下面通过几个示例看看get请求参数传递。
1、基础类型参数
[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请求最基础的参数传递方式。
2、实体作为参数
还记得get和post请求的区别吗?其中有一个区别就是get请求的数据会附在URL之后(就是把数据放置在HTTP协议头中),而post请求则是放在http协议包的包体中。
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 GetAllChargingData([FromUri]TB_CHARGING obj)
{
return "ChargingData" + obj.ID;
}
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) { }
});
如果你不想使用[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;
}
二、post请求
在WebApi的RESETful风格里面,API服务的增删改查,分别对应着http的post/delete/put/get请求。我们下面就来说说post请求参数的传递方式。
1、基础类型参数
post请求的基础类型的参数和get请求有点不一样,我们知道get请求的参数是通过url来传递的,而post请求则是通过http的请求体中传过来的,WebApi的post请求也需要从http的请求体里面去取参数。
$.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;
}
上面讲的都是传递一个基础类型参数的情况,那么如果我们需要传递多个基础类型呢?按照上面的推论,是否可以([FromBody]string NAME, [FromBody]string DES)这样写呢。
[HttpPost]
public object SaveData(dynamic obj)
{
var strName = Convert.ToString(obj.NAME);
return strName;
}
$.ajax({
type: "post",
url: "http://localhost:27221/api/Charging/SaveData",
contentType: 'application/json',
data: JSON.stringify({ NAME: "Jim",DES:"备注" }),
success: function (data, status) {}
});
通过dynamic动态类型能顺利得到多个参数,省掉了[FromBody]这个累赘,并且ajax参数的传递不用使用"无厘头"的{"":“value”}这种写法,有没有一种小清新的感觉~~有一点需要注意的是这里在ajax的请求里面需要加上参数类型为Json,即 contentType: 'application/json',
这个属性。
推荐用法
通过上文post请求基础类型参数的传递,我们了解到了dynamic的方便之处,为了避免[FromBody]这个累赘和{"":“value”}这种"无厘头"的写法。
2、实体作为参数
(1)单个实体作为参数
上面我们通过dynamic类型解决了post请求基础类型数据的传递问题,那么当我们需要传递一个实体作为参数该怎么解决呢?
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类型的对象即可。
(2)实体和基础类型一起作为参数传递
有些时候,我们需要将基础类型和实体一起传递到后台,这个时候,我们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;
}
3、数组作为参数
(1)基础类型数组
[HttpPost]
public bool SaveData(string[] ids)
{
return true;
}
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) { }
});
(2)实体集合
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;
}
4、后台发送请求参数的传递
上面写了那么多,都是通过前端的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);
}
三、put请求
WebApi里面put请求一般用于对象的更新。它和用法和post请求基本相同。同样支持[FromBody],同样可以使用dynamic。
1、基础类型参数
$.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;
}
2、实体/数组作为参数
和post请求相同。
四、delete请求
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;
}