簡體   English   中英

如何在Global.asax.cs文件中全局聲明Filter屬性

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

我在我的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);                         
    }
 }

我收到一個錯誤:不允許過濾。 我怎樣才能在全球范圍內宣布?

謝謝。

我認為添加空檢查對您有用。

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

    }
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM