I am posting a data with xhr in the project I am coding. A json reaches the Controller but if I use [FromBody] I get error code 415. If I don't use it, the incoming json looks empty.
Controller
[HttpPost]
[IgnoreAntiforgeryToken]
[Route("revizedCategoryzfc")]
public void revizedCategoryzfc([FromBody]Category model)
{
if (model.fileCode != null)
{
System.Console.WriteLine(model.fileCode);
}
System.Console.WriteLine("Girdi");
}
POST XHR CODE
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
}))
}
})
Error
CodePudding user response:
Since you user json strngify and frombody, you have to add this header to your xhr
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");