简体   繁体   中英

Ignoring ActionFilterAttribute, although explicitly defined on controller / action

I've got an ASP.NET middleware in the form of ActionFilterAttribute .

For example:

[CacheResponse(Seconds = 3)]
public async Task<IHttpActionResult> Echo(string userId, string message, string queryString)
{
    await Task.Delay(150);
    return Ok(new {Action = "Echo", UserId = userId, Message = message, QueryString = queryString});
}

The attribute CacheResponse is a nuget, I cannot touch its code. Yet I would like to have a feature-on/off configuration, so if I want to disable the cache mechanism, I won't have to do changes in the code.

How could I "cancel" the subscription of some controllers / actions to attributes? even though it's explicitly decorated with it?

I'm looking for a piece of code to run on webrole startup, that given the configuration value for the feature-on/off would cancell the decoration.

Thank you

I have implemented Nikolaus's idea. Code might look like:

public class ConfigurableCacheResponseAttribute : CacheResponseAttribute
{
    //Property injection
    public IApplicationConfig ApplicationConfig { get; set; }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        if (this.ApplicationConfig.Get<bool>("CashingEnabled"))
        {
            base.OnActionExecuted(actionExecutedContext);
        }
    }

    public override Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
    {
        if (this.ApplicationConfig.Get<bool>("CashingEnabled"))
        {
            return base.OnActionExecutedAsync(actionExecutedContext, cancellationToken);
        }

        return Task.CompletedTask;
    }

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (this.ApplicationConfig.Get<bool>("CashingEnabled"))
        {
            base.OnActionExecuting(actionContext);
        }
    }

    public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
    {
        if (this.ApplicationConfig.Get<bool>("CashingEnabled"))
        {
            return base.OnActionExecutingAsync(actionContext, cancellationToken);
        }

        return Task.CompletedTask;
    }
}

How to use dependency injection with filter attribute you could find here .

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