0

在我的 WebApi 2 应用程序中,我的基本控制器中有一个操作过滤器属性,该属性具有一个布尔属性,其默认值可以在构造函数中设置:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyActionFilterAttribute : ActionFilterAttribute
{
  public bool MyProperty {get; set;}

  public MyActionFilterAttribute(bool myProperty = true)
  {
    MyProperty = myProperty;
  }

  public override void OnActionExecuting(HttpActionContext actionContext)
  {
    if(MyProperty)
    {
        //DO Something
    }
  }
}

我还在CustomValidatorFilterwebApi config 中进行了配置:

config.Filters.Add(new CustomValidatorFilterAttribute());

在我的控制器的某些操作中,我想通过设置 to 的值来覆盖 MyActionFilterAttribute 的行为MyPropertyfalse我已将其添加OverrideActionFilters到我的操作中:

[OverrideActionFilters]
[MyActionFilterAttribute(myProperty: false)]
public IHttpActionResult MyCation()
{
  //Some staff here
}

但是现在我的自定义验证由于使用而不再起作用OverrideActionFilters,有没有办法重新定义 OverrideActionFilters,或者只是列出要覆盖的过滤器。谢谢您的帮助。

4

1 回答 1

1

我创建了一个特定属性DoMyPropertyAttribute,然后从MyActionFilterAttribute. 在MyActionFilterAttribute我检查动作是否有`DoMyPropertyAttribute,如果有,我会做具体的工作:

public class DoMyPropertyAttribute : Attribute
{
}

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyActionFilterAttribute : ActionFilterAttribute
{
  public override void OnActionExecuting(HttpActionContext actionContext)
  {
    if(actionContext.ActionDescriptor.GetCustomAttributes<DoMyPropertyAttribute>().Any())
    {
        //DO Something
    }
  }
}

一般来说,如果我们想要覆盖一个动作过滤器,我们只需跳过它,然后创建一个与所需行为匹配的特定动作过滤器。要跳过动作过滤器,我们可以这样做:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyActionFilterAttribute : ActionFilterAttribute
{
  public override void OnActionExecuting(HttpActionContext actionContext)
  {
    if(actionContext.ActionDescriptor.GetCustomAttributes<SkipMyActionFilterAttribute>().Any())
     {
       return;
     }

    //Do something
  }
}
于 2018-12-13T15:30:20.597 回答