c# - 覆盖特定的操作过滤器
问题描述
在我的 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
}
}
}
我还在CustomValidatorFilter
webApi config 中进行了配置:
config.Filters.Add(new CustomValidatorFilterAttribute());
在我的控制器的某些操作中,我想通过设置 to 的值来覆盖 MyActionFilterAttribute 的行为MyProperty
,false
我已将其添加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
}
}
推荐阅读
- r - 具有动态列范围的行和
- angular - 基本 Angular 6 应用程序未显示绑定变量
- java - 如何在 Java 中有效地存储一组元组/对
- python - 是否可以用 numpy BUT 替换该模块中未包含的功能的循环
- csv - 对存储在 AWS S3 中的大型 CSV 文件进行数据屏蔽
- javascript - 如何从 SSJS 访问 CSJS 函数?
- swift - Swift 4,泛型为什么我需要在这里转换为 T ?
- php - 如何连接到两个不同服务器上的多个 MySQL 数据库
- kotlin - 如何在 kotlin 中收集对流?
- python-2.7 - 树莓派上的 pysnmp