[英]WebAPI, [FromBody] string, application/json, Error 415 (Unsupported Media Type)
我有一個 WebAPI 項目 (c#),我用我的頁面 (Index.cshtml) 測試它:
<html>
<head>
...
</head>
<body>
<script src="@Url.Content("~/Scripts/jquery-3.2.1.js")" type="text/javascript"></script>
<script type="text/javascript">
function GetData() {
$.ajax({
url: "http://localhost:0000/api/test/test/cox/Test",
type: 'POST',
dataType: 'json',
data: JSON.stringify("Hello!!!"),
crossDomain: true,
processData: false,
contentType: 'application/json, charset=utf-8',
headers: { User: "test", Password: "test" },
success: function (q, w, e) {
alert(JSON.stringify(q));
},
error: function (q, w, e) {
alert("error: " + w);
}
});
}
</script>
<p>
<button onclick="GetData()">GetData</button>
</p>
</body>
</html>
此頁面調用我的方法:
[HttpPost]
[ResponseType(typeof(IEnumerable<СompositeType>))]
public HttpResponseMessage Test(string cox, [FromBody] string str)
{
...
}
我收到錯誤:415“不支持的媒體類型”。 我讀到了這個錯誤,有人說contentType: 'application/json, charset=utf-8'
會解決這個問題。 我知道屬性 [FromBody] 調用contentType: 'application/json'
進行轉換,但我不明白為什么我有錯誤 415。
我找到了解決方案,但這有點作弊。 (我想說:“謝謝!)”,以獲取答案。
第一 。 我改變了這個:
data: JSON.stringify({"str":"Hello!!!"}),
contentType: 'application/json; charset=utf-8',
第二 。 我改變了這個:
[HttpPost]
[ResponseType(typeof(IEnumerable<СompositeType>))]
public HttpResponseMessage Test(string cox, [FromBody] Test str)
{
...
}
第三 。 我添加了一個新類:
public class Test
{
public string str { set; get; }
}
嘗試從 [FromBody] 更改為 [FromForm]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.