How to send a post to an AspNetCore API without converting the date using Json.Stringify

0
Hello, I'm starting to work with ASPNET Core and there's a problem in working logic that I can not accept (I understand as a dumb thought anyway). Let's look at the examples:

  

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 ...)

    
asked by anonymous 03.05.2017 / 20:33

1 answer

0

As Thiago Silva said, I really needed to create a class with the methods that would be appropriate to relate the content that is going to be posted. How do I get it from Javascript where we can have generic elements, I thought that using object would have the same behavior (which is not the case) ... My solution looks like this:

A new class: FooModel

namespace AppTest.Models {
    class FooModel {
        string bar { get; set; }
    }
}

Implement the class in existing code

using AppTest.Models;

namespace AppTest.Controllers
{
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class FooController : Controller
    {
        [HttpPost]
        public JsonResult Post([FromBody] FooModel req)
        {
            return Json(req);
        }
    }
}

    
05.09.2017 / 15:57