我剛剛和這個和.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