Reputation: 5578
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
Upvotes: 0
Views: 249
Reputation: 1915
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.
Upvotes: 1