1 問題
在調用webapi post 提交時出現 415 Unsupported Media Type 錯誤
前端代碼如下:
$.post("/api/student/poststudent",
{ name: "張三", age: 21 },
function () {
});
請求結果如下:
415錯誤的解釋是服務器無法處理請求附帶的媒體格式。查看了HTTP請求頭部文件,發現content-type跟我們的json格式不同。
2 解決方案
在ajax請求中添加content-type設置為application/json,然后記得將數組對象格式化為json對象JSON.stringify()。
$.ajax({
url: "/api/student/poststudent",
type: 'POST',
data:JSON.stringify({ name: "張三", age: 21 }),
success:function () {
},
dataType: "json",
contentType: "application/json"
});
請求結果如下:
大功告成!