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:
Next is to
update ConfigureServices method under Startup class:
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);
}
}
}
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.
Comments
Post a Comment