gpt4 book ai didi

javascript - jQuery GET 参数在服务器端始终为空

转载 作者:行者123 更新时间:2023-12-02 22:27:29 26 4
gpt4 key购买 nike

我不知道我错过了什么。

传递复杂的自定义对象时一切正常,但当我尝试传递简单的 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`!
}

最佳答案

您获得 id 参数的 null 值的原因是 [FromBody]。从技术上讲,当您使用 jQuery 向服务器发送 GET 请求时,数据将显示在查询参数中,而不是请求正文中。

您需要在后端做的只是删除[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] 的文档您可以阅读以下内容:

To force Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter.

您的数据显示在查询字符串中,请检查 Chrome 中的网络选项卡:

enter image description here

enter image description here

希望这会有所帮助!

关于javascript - jQuery GET 参数在服务器端始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59019354/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com