MVC 4 Web API register filter

后端 未结 1 1958
礼貌的吻别
礼貌的吻别 2021-02-14 08:46

I am using MVC 4 Web API to create a service layer for an application. I am trying to create a global filter that will act on all incoming requests to the API. Now I understan

相关标签:
1条回答
  • 2021-02-14 09:28

    The following should work. We actually use this for our web API project.

    GlobalConfiguration.Configuration.Filters is of type HttpFilterCollection

     var filters = System.Web.Http.GlobalConfiguration.Configuration.Filters;
     filters.Clear();
     filters.Add(new ValidationActionFilterAttribute());
    
     public class ValidationActionFilterAttribute : FilterAttribute, IActionFilter, IFilter
     {
        ...
     }
    

    Also, if you're working in a project that contains both MVC and WebAPI assembilies, could you check what's the namespace your ActionFilterAttribute's namespace. It's fairly confusing cause there are two ActionFilterAttributes under both:

      System.Web.Http.Filters
       System.Web.Http.Mvc
    

    Source: Why is my ASP.NET Web API ActionFilterAttribute OnActionExecuting not firing?

    It appears that you will need to have two filters, one for API and one for MVC. You can factor the common code into a separate class, and then just use the specific filter to call through to your common class, thus not violating DRY and essentially using the actual filters as wrappers which can be registered as filters.

    0 讨论(0)
提交回复
热议问题