我刚刚和这个和.NET Core Web API有过一段时间。所以希望能够节省时间:对于我来说,实际问题很简单 - 我没有转换为正确的类型(注意,@达林斯答案使用VM而不是字符串)。
模板中的默认类型为string
。我想因为我们发送字符串化的JSON,我们会看到一个JSON字符串,但事实并非如此。我必须使它成为正确的类型。
E.g.这失败
[EnableCors("AllowAll")]
[HttpPost]
public HttpResponseMessage Post([FromBody]string value)
{
// Do something with the blog here....
var msg = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
return msg;
}
但是,这工作。
[EnableCors("AllowAll")]
[HttpPost]
public HttpResponseMessage Post([FromBody]Blog value)
{
// Do something with the blog here....
var msg = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
return msg;
}
Ajax调用
function HandleClick() {
// Warning - ID's should be hidden in a real application
// - or have covering GUIDs.
var entityData = {
"blogId": 2,
"url": "http://myblog.com/blog1",
"posts": [
{
"postId": 3,
"title": "Post 1-1",
"content": "This is post 1 for blog 1",
"blogId": 2
},
{
"postId": 4,
"title": "Post 1-2",
"content": "This is post 2 for blog 1",
"blogId": 2
}
]
};
$.ajax({
type: "POST",
url: "http://localhost:64633/api/blogs",
async: true,
cache: false,
crossDomain: true,
data: JSON.stringify(entityData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (responseData, textStatus, jqXHR) {
var value = responseData;
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.');
}
});
}
非常有用的部分:邮政有效载荷是在这种形式'= somevalue'...我疯了试图找出为什么不为我工作。我以'key = value'的形式拥有它。那谢谢啦! – Learner
'='+的上层解决方案很好,但不需要指定其内容类型,因为默认的ajax内容类型是“contentType:'application/x-www-form-urlencoded; charset = utf-8',“:] – dlght