2017-09-17 1 views
0

definiert Ich habe eine ASP.NET-Middleware in Form von ActionFilterAttribute.Ignorieren ActionFilterAttribute, obwohl explizit auf Controller/Aktion

Zum Beispiel:

[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}); 
} 

Das Attribut CacheResponse ein nuget ist, kann ich nicht seinen Code berühren. Noch möchte ich eine Feature-on/off-Konfiguration haben, also wenn ich den Cache-Mechanismus deaktivieren möchte, muss ich keine Änderungen im Code vornehmen.

Wie könnte ich das Abonnement einiger Controller/Aktionen auf Attribute "abbrechen"? obwohl es explizit damit verziert ist?

Ich bin auf der Suche nach einem Code für den Start von webrole, dass bei gegebenem Konfigurationswert für das Feature-on/off die Dekoration abbrechen würde.

Vielen Dank

+0

Wie registrieren Sie die Middleware in der Startup.cs? – Nikolaus

+0

Ich registriere nichts in 'Startup.cs'. Ich setze einfach ein Attribut auf den Controller/Action und es geschieht magisch :) – johni

+0

Sie können das Attribut mit Ihrem benutzerdefinierten Attribut umbrechen, wo Sie entscheiden, ob Sie es verwenden oder nicht. Aber ich bin kein Experte für Filterattribute. – Nikolaus

Antwort

1

Ich habe Nikolaus Idee umgesetzt. Code könnte wie folgt aussehen:

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; 
    } 
} 

Wie Dependency Injection mit Filter verwenden Attribut Sie here finden konnten.

Verwandte Themen