【发布时间】:2019-02-11 08:51:20
【问题描述】:
我在将 ajax 数据从我的 javascript 文件发送到我的 c# 控制器时遇到问题。我在我的 c# 程序中收到“错误请求错误”,我得到这个的原因是因为我使用 ajax 发送的数据参数“result”没有被 c# 接收,并且 c# 变量保持为空。我知道 Ajax 正在路由到正确的控制器,因为它正在调用该方法,但是由于某种原因,c# 没有收到变量“result”。
这是我的 ajax 请求。
$.ajax({
type: 'POST',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: { 'result' : result },
url: "https://localhost:44374/api/task",
cache: false,
success: function (data) {
// Process the received data.
}
});
这是我的 c# 控制器
[HttpPost]
public ActionResult<string> Get(string result)
{
string id = result;
getTaskContent(id);
return id;
}
将Ajax改为GET后,程序运行,输出为:
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:44374/api/task/1108164994166723?_=1549876832637 application/x-www-form-urlencoded; charset=UTF-8
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 17.8526ms 404
但由于某种原因,C# Actionresult 方法没有得到执行。
看到URL是localhost:44374/api/task/1108164994166723?_=1549876832637,结果变量是1108164994166723,我不知道?_=1549876832637部分是怎么来的。如果我在窗口中提醒结果变量,它只是 1108164994166723
解决方案
更改为 GET 而不是 POST 以及将 Ajax 中的 URL 更改为 url: "localhost:44374/api/task?result=" + result 的组合,完成了这项工作。
正确的 Ajax 代码是:
$.ajax({
type: 'GET',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
url: "https://localhost:44374/api/task?result=" + result
});
【问题讨论】:
-
您的控制器有一个
HttpGet注释过滤器,而您正在为初学者发出一个POST请求...不确定它是否调用了正确的方法。 -
为什么结果后面有逗号?如果发送的数据是 JSON 格式,则不能在 json 末尾添加逗号
-
这两个都没有解决问题,去掉逗号,改成Get
-
您的第二个问题是数据没有像使用 GET 请求那样设置。将数据添加到 url 而不是请求的正文。
-
我尝试将结果变量添加到 URL 中,但我被困在如何在 c# 中检索变量
标签: javascript c# jquery asp.net ajax