Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have implemented one action filter in my MVC project. Now I want to add it globally so that I do not need to write filter attribute just above the action methods. I am using BundleMinifyInlineJsCss nuget package.

I have tried with following code in 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 am getting an error: Filtering is not allowed. How can I declare it Globally?

Thanks.

like image 414
Ankita Avatar asked Sep 09 '15 06:09

Ankita


1 Answers

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);

    }
 }
like image 64
Ajinder Singh Avatar answered Sep 24 '22 02:09

Ajinder Singh