I have a very simple server call like this:
[HttpPost]
[AllowAnonymous]
public JsonResult Test(TestRequestModel requestModel)
{
//do stuff
return Json(new { result.Success });
}
My TestRequestModel looks like this:
public class TestRequestModel
{
public string Email { get; set; } = string.Empty;
}
I am trying to do a POST request to the server. But for a complex list of reasons I need to be using XMLHttpRequest instead of $.ajax. To do this I am going to show you how I did it in ajax and then how I did it with XMLHttpRequest.
First here is how I call my server:
function MyTestFunction() {
let parameters = {
Email: "[email protected]"
}
CallServer(function () {
//Do stuff
}, function () {
//Do other stuff
}, "/Home/Test", parameters)
}
Ajax:
function CallServer(resolve, reject, path, parameters) {
$.ajax({
type: "POST",
url: path,
data: AddAntiForgeryToken(parameters),
success: function (response) {
//do stuff
},
error: function (xhr) {
//do stuff
},
complete: function () {
//do more stuff
}
});
}
XMLHttpRequest Way:
function CallServer(resolve, reject, path, parameters) {
let xhr = new XMLHttpRequest();
xhr.open("POST", path, true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.setRequestHeader('RequestVerificationToken', GetMyToken());
xhr.onreadystatechange = function (e) {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200 || xhr.status === 201) {
//do stuff
}
else {
//do other stuff
}
}
};
xhr.send(JSON.stringify(parameters));
}
If I run the above code the ajax way, then it works without issues. If I try to do it the XMLHttpRequest way then my request model gets created but the Email field is not populated. Now I found that I can solve this by adding [FromBody] on the request model and it does work, I tested it and no problems.
Also, as I read online and hopefully understood correctly, but ajax uses XMLHttpRequest behind the hood right?
So why do I have to add [FromBody] on my controller for this to work? Is there a way I can modify my XMLHttpRequest so that it is not needed? The solution I am looking for how to not have to specify [FromBody] on a json post request to .net core server.