How to declare the Filter attribute globally in the Global.asax.cs file

I implemented one action filter in my MVC project. Now I want to add it globally, so I don’t need to write a filter attribute just above the action methods. I am using bundleMinifyInlineJsCss nuget package.

I tried using the following code in the Global.asax.cs file:

GlobalFilters.Filters.Add(new ReplaceTagsAttribute());

Here is my filter code:

 public class ReplaceTagsAttribute : ActionFilterAttribute
 {
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Filter = new BundleAndMinifyResponseFilter(filterContext.HttpContext.Response.Filter);                         
    }
 }

I get an error: Filtering is not allowed. How can I declare it globally?

Thanks.

+4
source share
1 answer

I think adding a null check will work for you.

    public class ReplaceTagsAttribute : ActionFilterAttribute
 {
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
       var response = filterContext.HttpContext.Response;
 if (response.Filter == null) return; // <-----
response.Filter = new BundleAndMinifyResponseFilter(response.Filter);

    }
 }
+3
source

Source: https://habr.com/ru/post/1606535/


All Articles