我不知道我在想什么。
传递复杂的自定义对象时,一切正常,但是当我尝试传递简单的int或字符串时,我得到null
这里是客户端的ajax调用:
var id = 1;
$.ajax({
type: "GET",
url: "/api/APICalls/MethodName",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(id), // or JSON.stringify({id: id}) or just id
dataType: "json",
success: function (data) {
console.log(data);
},
error: function (data) {
alert(data.responseText);
}
});
在服务器端,方法如下:
[HttpGet]
public void MethodName([FromBody] string id)
{
// Do something with id... Doesn't matter... It is `null`!
}
获得null
参数的id
值的原因是[FromBody]
。从技术上讲,当您使用GET
向服务器发送jQuery
请求时,数据将显示在查询参数中,而不是在请求正文中。
您需要在后端执行的操作只是如下删除[FromBody]
:
[HttpGet]
public void MethodName(string id)
{
// Now you should be able to access the value of id
}
从客户端发送数据如下:
var id = 1;
$.ajax({
url: '/api/APICalls/MethodName',
type: 'GET',
data: {id: id},
success: function (data) {
console.log(data);
},
error: function (err) {
console.error(err);
}
});
从[FormBody]
的文档中,您可以阅读以下内容:
要强制Web API从请求正文中读取简单类型,请将
[FormBody]
属性添加到参数中。
您的数据显示在查询字符串中,请在Chrome中检查“网络”标签:
[FromBody]
我希望这会有所帮助!