Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Required attribute is not working for the body request at the method of API endpoint

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?

like image 242
Learner Avatar asked Aug 31 '25 04:08

Learner


1 Answers

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.

like image 182
kubson Avatar answered Sep 02 '25 16:09

kubson