简体   繁体   中英

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.

That said, one way to do it would be for the filter to drop a value in the context Items collection :

context.HttpContext.Items["something"] = something;

Then that can be read later, anywhere (within the same request) that has access to the 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.

    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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM