Validate the Model State Globally in .NET Core MVC: .NET Core Quick Posts
We take a look at how to use model states globally and thus reduce the amount of code that needs to be written for you app.
Join the DZone community and get the full member experience.
Join For FreeIn this post, we will see an awesome feature of .NET Core which will make your life a bit easier.
We are talking about the auto-validation of models in .NET Core.
I remember putting a ModelState.IsValid
check in almost all POST, PUT, DELETE, etc. action methods of a controller. This check was used to check whether the Model has any errors or not.
So if IsValid
returns false then the Model contains some validation error and the controller would not allow the model to pass into the controller.
If you are from an MVC background, then you'll be quite familiar with the below code:
if (!ModelState.IsValid) {
// return bad request or errors or redirect it to somewhere
}
As we can see above, we have to put this check into many actions and many controllers. But what if we can add this check globally?
I know we can create some custom attributes and we can add those attributes above the action methods or the controllers. But what if we can add this validation check globally without putting the attributes above the actions or controllers?
Interesting right?
It is very much possible in .NET Core. We just need to add a few lines of code which will work for all the controllers and actions.
Add a Custom Filter Class
Let's add the custom filter class,which we will name ValidateMyModelAttribute
, as shown below:
public class ValidateMyModelAttribute: ActionFilterAttribute {
public override void OnActionExecuting(ActionExecutingContext context) {
if (!context.ModelState.IsValid) {
context.Result = new BadRequestObjectResult(context.ModelState); // it returns 400 with the error
}
}
}
Here, the filter will return BadRequest
if the Model is not valid.
Add a Custom Filter Globally
The next step is to add this custom filter globally in the Startup.cs
class. We will add this filter to the ConfigureService
method of the class, as shown below:
public void ConfigureServices(IServiceCollection services) {
services.AddMvc(options => {
options.Filters.Add(typeof(ValidateMyModelAttribute));
});
}
That is it. Now the model will be validated in all those required action methods, hence, you'll have no more headaches caused by adding tge same repetitive code in all your action methods.
Hope this helps.
You can find all of my .NET Core posts here.
Published at DZone with permission of Neel Bhatt, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments