前言:还记得刚使用WebApi那会儿,被它的传参机制折腾了好久,查阅了半天资料。如今,使用WebApi也有段时间了,今天就记录下API接口传参的一些方式方法,算是一个笔记,也希望能帮初学者少走弯路。本篇针对初初使用WebApi的同学们,比较基础,有兴趣的且看看。
本篇打算通过get、post、put、delete四种请求方式分别谈谈基础类型(包括int/string/datetime等)、实体、数组等类型的参数如何传递。
一、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请求时想将实体对象做参数直接传递到后台,是否可行呢?我们来看看。
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请求

原来,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;
}
?我们以实体对象作为参数来传递写写代码试一把。
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里面进入断点

尝试成功。
三、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请求相同。
3、数组作为参数
和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;
}

五、总结
以上比较详细的总结了WebApi各种请求的各种参数传递。每种情况都是博主实际代码测试过的,内容不难,但如果刚接触这么些东西还是需要一点时间去熟悉的,在此做个总结,希望能帮到刚刚接触WebApi的园友们。如果本文能帮到你,不妨推荐下,您的推荐是博主继续总结的动力! |