【问题标题】:How to declare Filter attribute globally in Global.asax.cs file如何在 Global.asax.cs 文件中全局声明过滤器属性
【发布时间】:2015-09-09 06:01:53
【问题描述】:

我在我的 MVC 项目中实现了一个动作过滤器。现在我想全局添加它,这样我就不需要在操作方法上方编写过滤器属性。我正在使用 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);                         
    }
 }

我收到一个错误:不允许过滤。如何在全球范围内声明它?

谢谢。

【问题讨论】:

  • 您将此属性应用于 Controller 或 Action 方法?
  • 对于动作方法。如果我手动将属性写入 Action 方法,我可以成功添加它。但我想将此添加到所有操作方法中。
  • 试试GlobalConfiguration.Configuration.Filters.Add(..)
  • @AmitKumarGhosh:在 Global.asax.cs 文件中。对吗?
  • @AmitKumarGhosh:它给了我一个错误:Nop.Web.Customization.ActionFilter.ReplaceTagsAttribute' is a 'type' but is used like a 'variable'

标签: c# asp.net-mvc actionfilterattribute


【解决方案1】:

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

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

    }
 }

【讨论】:

  • 是的,现在可以了。为什么我们需要这样做?你能解释一下吗?
  • 当时似乎不允许过滤所以应用检查以确保允许过滤。
  • 什么时候不允许过滤?
  • 其实我不能说。可能会尝试从一开始就进行调试,并在您的过滤器被调用时检查。
猜你喜欢
  • 2013-02-21
  • 1970-01-01
  • 1970-01-01
  • 2010-10-30
  • 2017-03-11
  • 2017-07-12
  • 2018-03-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多