I have simple API methods. I need to check whether the body request is null.
For example:
[HttpPost]
public ActionResult<Product> CreateProduct([FromBody] Product product)
{
if (product == null)
{
return BadRequest("request is empty");
}
_someService.Create(product);
}
But I would like to avoid this repeating piece of code in all my API methods:
if (product == null)
{
return BadRequest("request is empty");
}
So I tried to use attribute [Required]
and send an empty body in the request:
[HttpPost]
public ActionResult<Product> CreateProduct([FromBody] [Required] Product product)
{
// this piece of code should not be run because "product" is null
_someService.Create(product);
}
However, no errors are thrown.
Is it possible to use [Required]
in API methods as I have shown here?
Easiest way is to use the [ApiController]
attribute for your controller. You can read more in the docs here https://learn.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-9.0#apicontroller-attribute
Automatic HTTP 400 responses
The
[ApiController]
attribute makes model validation errors automatically trigger an HTTP 400 response. Consequently, the following code is unnecessary in an action method:C#Copy
if (!ModelState.IsValid) { return BadRequest(ModelState); }
ASP.NET Core MVC uses the ModelStateInvalidFilter action filter to do the preceding check.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With