【发布时间】:2017-04-30 14:43:14
【问题描述】:
我遇到了 ASP.NET Core MVC 中的模型绑定问题。我有这个端点,当从 Javascript 调用时会被命中,但 postData 始终为空。
[HttpPost("/somepost")]
public string SomePost([FromBody] PostData postData)
{
return "Got It!";
}
public class PostData
{
public int ID { get; set; }
public string[] ListOrArray { get; set; } // Doesn't matter if this ends up a List or an Array
}
这个端点被 $.click 函数击中:
$('img.some-image').click(function () {
array = ['sample data', 'some more'];
data = {
ID: 1,
ListOrArray: array
};
$.ajax({
type: 'POST',
url: '/somepost',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: data,
success: function (result) {
console.log('Received: ');
console.log(result);
}
});
});
我猜测问题出在模型绑定上,但我不确定。我见过小写 Javascript 对象属性名称的示例,但这对我来说没有任何改变。
我还必须从 POST 中删除 [ValidateAntiForgeryToken],但我更愿意将其重新添加。我猜我必须将令牌添加到 GET 请求中,以便我可以将其提交给 POST,但我还没有弄清楚如何做到这一点。不过,我认为这与我的问题无关。
我已经搜索了答案和示例,但没有一个对我有用。 ASP.NET Core 是相当新的,所以没有太多内容。我使用的是 1.1.0 版本。
【问题讨论】:
-
要添加令牌,只需在您的“数据对象”中包含
__RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val();
标签: javascript c# asp.net-core asp.net-core-mvc