Saturday, August 3, 2019

Avoid duplication of ModelState.IsValid in ASP.NET Core

Generally, whenever something is to be saved to the database or to any other place, as a best practice almost everyone use to validate the state of the model. So, if state of model is valid, we proceed and if model state is invalid, we handle it as a bad request. This looks something like this:
If(!ModelState.IsValid)

{

    // create bad request object

}       
 
So, all these were done by using the IsValid property.

Problem

Now what if we have to perform the same validation for all the models. Are we going to write the same validation in each and every controller?

Of course, No.

Solution

Rather than duplicating the same code in each and every controller, we can create a global filter. This global filter has few methods, but for our purpose we can go with OnActionExecuting.
public class ValidateModelStateFilter : ActionFilterAttribute

{
    
   public override void OnActionExecuting(ActionExecutingContext context)

    {

        if (!context.ModelState.IsValid)

        {

           context.Result = new BadRequestObjectResult(context.ModelState);

        }

    }

}
       
 
Next is to update ConfigureServices method under Startup class:
services.AddMvcCore(options =>

{

     options.Filters.Add(typeof(ValidateModelFilter));

})
Once above changes are done, we need not to repeat the same ModelState validation check in each and every controller.

Hope this tip would be useful.

1 comment:

  1. 먹튀사이트 잡는 고릴라의 먹튀검증 통과 메이저토토사이트 안전놀이터 추천 훌륭한 먹튀검증을 통한 안전토토사이트를 추천합니다 고릴라만의 검증 시스템은 특별합니다 전세계적인 먹튀검증을 인전받은 최고의 메이저사이트 추천을 합니다 자세한 내용은 내 웹 사이트를 방문하십시오 먹튀검증.

    ReplyDelete