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.
If you
POSTyour model inside the body withContent-Type: application/jsonthen you have to tell theModelBinderto 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]So this works without [FromBody] in ASP.NET Core 2.1 and above