Apply [FromBody] attribute to all controller actions in .net core

2.6k Views Asked by At

Having a simple .NET Core API with your models posted as JSON in request body, how to have [FromBody] attribute applied to all controller methods?

[Route("api/simple")]
public class SimpleController : ControllerBase
{
    [HttpPost]
    public IActionResult Post([FromBody] MyRequest request)
    {
        return Ok();
    }
}

If I remove the [FromBody] attribute, all model properties will be null.

1

There are 1 best solutions below

1
Mohsen Afshin On

If you POST your model inside the body with Content-Type: application/json then you have to tell the ModelBinder to read the model from body by applying [FromBody] attribute.

But adding [FromBody] to all of your API actions makes you feel bad.

Just apply the [ApiController] to your controller and then you don't need [FromBody] anymore.

Microsoft Doc definition of [ApiController]

Indicates that a type and all derived types are used to serve HTTP API responses.

Controllers decorated with this attribute are configured with features and behavior targeted at improving the developer experience for building APIs.

So this works without [FromBody] in ASP.NET Core 2.1 and above

[Route("api/simple")]
[ApiController]
public class SimpleController : ControllerBase
{
    [HttpPost]
    public IActionResult Post(OrderRequest request)
    {
         return Ok();
    }
}