【问题标题】:Creating custom FilterAttribute for method parameters为方法参数创建自定义 FilterAttribute
【发布时间】:2013-02-05 09:41:51
【问题描述】:

是否可以为传入参数创建自定义FilterAttribute? 属性大多用于方法和类;

例如我的想法是:

public HttpResponseMessage GetAll([CultureInfo]string culture)

{ if(valid) { // code here } }

CultureInfo 是一个继承自 ActionFilterAttribute 的类 (CultureInfoAttribute),我可以在其中使用 2 个称为 OnActionExecuted 和 OnActionExecuting 的方法。 在我的课堂上,我使用了下一个属性,所以我可以在参数上使用它:

[AttributeUsage(AttributeTargets.Parameter)]

当我构建并调用 GetAll("culture") 时,我的自定义过滤器中的 OnActionExecuting 方法永远不会被调用....当我将属性放在我的方法 GetAll() 之上时它会调用。

谁有这方面的经验?

我想这样做的原因是因为我可以将属性放在不同的参数上,而不是一次放在整个方法上。

【问题讨论】:

    标签: c# asp.net-mvc


    【解决方案1】:

    我想你的问题已经回答了here:

    您应该像这样在GlobalFilters 中注册您的过滤器Global.asax.cs

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new CultureInfoAttribute());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-09
      • 1970-01-01
      • 1970-01-01
      • 2016-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多