在我的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
}
}
}
我还有一个在webApi-config:中配置的CustomValidatorFilter
config.Filters.Add(new CustomValidatorFilterAttribute());
在我的控制器的某些操作中,我想通过将MyProperty
的值设置为false
来覆盖MyActionFilterAttribute的行为,我已经将OverrideActionFilters
添加到我的操作中:
[OverrideActionFilters]
[MyActionFilterAttribute(myProperty: false)]
public IHttpActionResult MyCation()
{
//Some staff here
}
但现在我的自定义验证由于使用了OverrideActionFilters
而不再工作,有没有任何方法可以重新定义OverrideActionFilters,或者只是列出要覆盖的过滤器。谢谢你的帮助。
我创建了一个特定的属性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
}
}