Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate ModelState.IsValid globally for all controllers

In my ASP.NET Core Controllers I always check if the ModelState is valid:

[HttpPost("[action]")]
public async Task<IActionResult> DoStuff([FromBody]DoStuffRequest request)
{
  if (!ModelState.IsValid)
  {
    return BadRequest("invalid parameters");
  }
  else
  {
    return Ok("some data"));
  }
}

Is there a way to check validity of the ModelState globally using a filter so I don't have to do this in every API item in every controller again? It would be nice if the action could rely on the modelstate being valid and not needing to check:

[HttpPost("[action]")]
public async Task<IActionResult> DoStuff([FromBody]DoStuffRequest request)
{
  return Ok("some data"));
}
like image 776
Sam Avatar asked Jan 26 '17 11:01

Sam


People also ask

What ModelState is IsValid validate?

ModelState. IsValid indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process. In your example, the model that is being bound is of class type Encaissement .

How can we check whether our model is valid or not at the controller level?

You need to check whether the submitted data is valid or not in the controller. In other words, you need to check the model state. Use the ModelState. IsValid to check whether the submitted model object satisfies the requirement specified by all the data annotation attributes.

What is ModelState IsValid in asp net core?

Model state represents errors that come from two subsystems: model binding and model validation. Errors that originate from model binding are generally data conversion errors. For example, an "x" is entered in an integer field.


1 Answers

For ASP.NET Core 2.0, to avoid applying attributes to all Controllers or Actions individually;

Define a filter:

namespace Test
{
    public sealed class ModelStateCheckFilter : IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context) { }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                context.Result = new BadRequestObjectResult(context.ModelState);
            }
        }
    }
}

Then in your Startup.cs, add it as filter:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(config =>
        {
            config.Filters.Add(new ModelStateCheckFilter());
        });
    }
like image 91
Mert Akcakaya Avatar answered Sep 18 '22 17:09

Mert Akcakaya