posts - 609,  comments - 13,  views - 64万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

1.GET请求传递参数

URL传参:http://localhost/ApiTest/test?id=1

API接收参数

[HttpGet]

public string GetUser(int id) { return "User:" + id; }

 

传递JSON对象:

$.ajax({

type: "get",

url: "http://localhost/ApiTest/test",

contentType: "application/json",

data: { id: "1" },

success: function (data, status) { if (status == "success") { $("#div_test").html(data); } }

});

API接收参数

[HttpGet]

public string GetUser([FromUri]UserDto obj) { return "User:" + 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;

}

注意:方法名以Get开头,WebApi会自动默认这个请求就是get请求,而如果你以其他名称开头而又不标注方法的请求方式,那么这个时候服务器虽然找到了这个方法,但是由于请求方式不确定,所以直接返回给你405——方法不被允许的错误。

POST传参:

单个参数:

$.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;}

多个参数,使用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;}

传递集合:

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;
}

来源:http://www.cnblogs.com/landeanfen/p/5337072.html

posted on   邢帅杰  阅读(164)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示