[英]How to access a Filter property in invoking class in ASP.NET Core
Is it possible to access a property in a Filter from the class that uses it? 是否可以从使用它的类中访问过滤器中的属性 ?
I want to be able to access the Client property in the Filter below 我希望能够访问下面的过滤器中的“ 客户端”属性
[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; } }
}
I agree with Camilo that this probably isn't a good idea - it's easy to break. 我同意Camilo的观点,这可能不是一个好主意-容易破解。
That said, one way to do it would be for the filter to drop a value in the context Items
collection : 也就是说,一种方法是过滤器在上下文Items
集合中删除一个值:
context.HttpContext.Items["something"] = something;
Then that can be read later, anywhere (within the same request) that has access to the HttpContext. 然后可以在任何具有HttpContext访问权限的位置(在同一请求内)读取该内容。
The danger of doing this is that if anyone changes how the filter works, or removes the filter entirely, code later on will break - and that's not obvious to anyone working in the code for the filter. 这样做的危险是,如果任何人更改了过滤器的工作方式或完全删除了过滤器,以后的代码都会中断-对于在过滤器代码中工作的任何人来说,这都不是显而易见的。
Use reflection to access the custom properties. 使用反射来访问自定义属性。 This is a really quick untested version, so please add proper null checks, casts, etc. 这是一个非常快速的未经测试的版本,因此请添加适当的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.
}
}
Since you potentially have multiple client attributes, you'll want to do some handling for that situation as well. 由于您可能具有多个客户端属性,因此您也需要针对这种情况进行一些处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.