0
Hello, I’m starting to work with ASPNET Core and there’s a problem in working logic that I can’t accept (I understand as a really dumb thought). Let’s go to the examples:
NOTE: in all tests I am using jQuery library to facilitate understanding.
If I work with a webserver Expressjs (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 the parameter data
in a string, using the resource data:JSON.stringify({bar:123})
.
This also happens with other PHP frameworks I’ve worked with (like Laravel, codeigniter, zend, etc).
Now, if I have an ASPNET Core solution, I am required 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);}
});
Back-end controller of the solution
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 I have to do the serialization of it in my front-end?
Question 2 - Is there any way I can configure the solution so that it always receives the "application/json" contenttype? (This on the server side and not on the front end...)
Why are you using Object as a parameter for your action? Try to create a class and pass the JSON properties that will work without needing JSON.stringify in the client.
– Thiago Silva