如何在Global.asax.cs文件

时间:2015-09-09 06:01:53

标签: c# asp.net-mvc actionfilterattribute

我在MVC项目中实现了一个动作过滤器。现在我想全局添加它,这样我就不需要在action方法之上编写filter属性了。我正在使用BundleMinifyInlineJsCss nuget包。

我尝试使用Global.asax.cs文件中的以下代码:

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

这是我的过滤器代码:

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

我收到错误:不允许过滤。我怎样才能在全球范围内宣布?

感谢。

1 个答案:

答案 0 :(得分:4)

我认为添加空检查对您有用。

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

    }
 }