DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Languages
  4. Validate the Model State Globally in .NET Core MVC: .NET Core Quick Posts

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.

Neel Bhatt user avatar by
Neel Bhatt
CORE ·
Aug. 26, 18 · Tutorial
Like (3)
Save
Tweet
Share
15.69K Views

Join the DZone community and get the full member experience.

Join For Free

In 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.

.NET POST (HTTP)

Published at DZone with permission of Neel Bhatt, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How and Why You Should Start Automating DevOps
  • Hidden Classes in Java 15
  • An Introduction to Data Mesh
  • Asynchronous HTTP Requests With RxJava

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: