javascript - ASP.NET Core 失败的 AJAX 发布请求
问题描述
我一直在尝试将信息对象传递给 .NET Core Controller 方法。传递单个字符串并接收很好。但是,当我尝试传递从表中获取的数据时,控制器没有接收到。请参阅下面的代码。
控制台错误输出
POST https://localhost:44366/home/GetInformation 415
MVC 控制器:也尝试过 [FromQuery]。它成功地获得了命中,但接收到空值。
public class HomeController : Controller
{
[HttpPost]
public string GetInformation([FromBody]Student student)
{
return "Hi " + student.Name;
}
}
JQuery AJAX: 我试过把 Raw 对象,直接作为数据发送对象
var fetcheddata = {
Id: col1,
Name: col2
};
$.ajax({
url: "home/GetInformation",
type: "POST",
data: JSON.stringify(fetcheddata),
beforeSend: function (xhr) {
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (data, status) {
//task
},
error: function (data, status) {
//task
}
});
虽然,使用带有这些参数的Fiddler,它工作正常。
POST https://localhost:44366/home/GetInformation HTTP/1.1
User-Agent: Fiddler
Content-Type: application/json
Host: localhost:44366
Content-Length: 28
{"Id": 1, "Name":"Cucumber"}
解决方案
尝试Content-Type
在您的 AJAX 请求上设置标头,您可以看到它存在于您的 Fiddler 请求中。
$.ajax({
...
contentType: 'application/json'
...
});
jQuery.ajax()的默认内容类型是'application/x-www-form-urlencoded; charset=UTF-8'
.