[英]How to access a Filter property in invoking class in ASP.NET Core
是否可以从使用它的类中访问过滤器中的属性 ?
我希望能够访问下面的过滤器中的“ 客户端”属性
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true)]
public class ClientAuthenticationAttribute : ActionFilterAttribute, IActionFilter
{
private ILogger _logger;
private GenericUnitOfWork _worker;
private bool _authRequired;
private Client _client;
public ClientAuthenticationAttribute(bool authRequired = true)
{
_authRequired = authRequired;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
...
base.OnActionExecuting(context);
}
public bool AuthRequired { get { return _authRequired; } }
public Client Client { get { return _client; } }
}
我同意Camilo的观点,这可能不是一个好主意-容易破解。
也就是说,一种方法是过滤器在上下文Items
集合中删除一个值:
context.HttpContext.Items["something"] = something;
然后可以在任何具有HttpContext访问权限的位置(在同一请求内)读取该内容。
这样做的危险是,如果任何人更改了过滤器的工作方式或完全删除了过滤器,以后的代码都会中断-对于在过滤器代码中工作的任何人来说,这都不是显而易见的。
使用反射来访问自定义属性。 这是一个非常快速的未经测试的版本,因此请添加适当的null检查,强制转换等。
var props = this.GetProperties();
foreach (PropertyInfo prop in props) {
var attrs = prop.GetCustomAttributes(true);
foreach (object attr in attrs.Where(a => a is ClientAuthenticationAttribute)) {
var client = ((ClientAuthenticationAttribute)attr).Client;
// ... do something with client.
}
}
由于您可能具有多个客户端属性,因此您也需要针对这种情况进行一些处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.