我正在編碼的專案中使用 XHR 發布資料。一個 JSON 到達控制器,但如果我使用[FromBody]我得到error code 415. 如果我不使用它,傳入的 JSON 看起來是空的。
控制器
[HttpPost]
[IgnoreAntiforgeryToken]
[Route("revizedCategoryzfc")]
public void revizedCategoryzfc([FromBody] Category model)
{
if (model.fileCode != null)
{
System.Console.WriteLine(model.fileCode);
}
System.Console.WriteLine("Girdi");
}
發布 XHR 代碼
async function makeRequest(method, url, model) {
return new Promise(function(resolve, reject) {
let xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function() {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response);
}else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function() {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send(model);
});
}
document.querySelector('.save-service').addEventListener('click', async () => {
for (var es of document.querySelectorAll('.category-item'))
{
await makeRequest('POST', '/zfc/revizedCategoryzfc', JSON.stringify({
"Name": es.querySelector('.service-name').value,
"fileCode": es.querySelector('.filecodas').value,
"CategoryId": es.querySelector('.zfc-id').value
}))
}
})
錯誤
![.net 核心 mvc 正在到達我發布的 json 控制器,但我無法讀取它。當我使用 [FromBody] 時,我也收到錯誤代碼 415](https://img.uj5u.com/2021/12/21/5433667bacf845759a91eadacb5f9a4b.png)
uj5u.com熱心網友回復:
由于您使用 json strngify 和 frombody,您必須將此標頭添加到您的 xhr
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/388233.html
