NOTE: In all tests I'm using the jQuery library to make it easier to understand.
If I work with an ExpressJS webserver (Node.JS) in a simple post to the server, I can make an ajax request like this:
$.ajax({
url:"api/foo",
method:"post",
data:{bar:123}, // <-- objeto sem serializar
success:function(res){console.log(res);},
error:function(res){console.log(res);}
});
In this case, it is not necessary to transform the object of parameter data
into a string, using the data:JSON.stringify({bar:123})
feature.
This also happens with other PHP frameworks I've worked on (such as laravel, codeigniter, zend, etc.).
Now, if I have an ASPNET Core solution, I have to make my request this way:
Request coming from the solution front-end
$.ajax({
url:"api/foo",
method:"post",
contentType:"application/json;charset=utf8", // <-- excesso de código desnecessário
data:JSON.stringify({bar:123}), // <-- excesso de código desnecessário
success:function(res){console.log(res);},
error:function(res){console.log(res);}
});
Controller in the solution backend
using Microsoft.AspNetCore.Mvc;
namespace AppTest.Controllers
{
[Produces("application/json")]
[Route("api/[controller]")]
public class FooController : Controller
{
[HttpPost]
public JsonResult Post([FromBody] object req)
{
return Json(req);
}
}
}
Question 1 - Is there any way I can compel ASPNET Core to SEMRPE accept the object without having to serialize it on my front end?
Question 2 - How can I configure the solution so that it always receives the contentType of type "application / json"? (This server side and not front end ...)