How can I centralize modelstate validation in asp.net mvc using action filters?

后端 未结 4 1828
一生所求
一生所求 2020-12-05 01:11

I write this code in several places and always repeat this logic:

public ActionResult MyMethod(MyModel collection)
{
    if (!ModelState.IsValid)
    {
              


        
4条回答
  •  自闭症患者
    2020-12-05 01:31

    Here is how to use the code from Khanh TO (from asp.net official site):

    To apply this filter to all Web API controllers, add an instance of the filter to the HttpConfiguration.Filters collection during configuration:

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Filters.Add(new ValidateModelAttribute());
    
            // ...
        }
    }
    

    Another option is to set the filter as an attribute on individual controllers or controller actions:

    public class ProductsController : ApiController
    {
      [ValidateModel]
      public HttpResponseMessage Post(Product product)
      {
        // ...
      }
    }
    

提交回复
热议问题