2016-12-12 1 views
3

In Asp.Net Core, wenn ein benutzerdefiniertes Stück Middleware erstellt und in seiner eigenen Klasse platziert wird, wie bekommt man Zugriff auf IHostingEnvironment aus der Middleware?Zugriff auf IHostingEnvironment in Middleware-Klasse

Zum Beispiel in meiner Klasse unten dachte ich, ich könnte IHostingEnvironment in den contstructor injizieren, aber es ist immer null. Haben Sie noch weitere Ideen, wie Sie auf IHostingEnvironment zugreifen können?

public class ForceHttps { 
    private readonly RequestDelegate _next; 
    private readonly IHostingEnvironment _env; 

    /// <summary> 
    /// This approach to getting access to IHostingEnvironment 
    /// doesn't work. It's always null 
    /// </summary> 
    /// <param name="next"></param> 
    /// <param name="env"></param> 
    public ForceHttps(RequestDelegate next, IHostingEnvironment env) { 
     _next = next; 
    } 


    public async Task Invoke(HttpContext context) { 
     string sslPort = ""; 
     HttpRequest request = context.Request; 


     if(_env.IsDevelopment()) { 
      sslPort = ":44376"; 
     } 

     if(request.IsHttps == false) { 
      context.Response.Redirect("https://" + request.Host + sslPort + request.Path); 
     } 

     await _next.Invoke(context); 

    } 
} 
+1

My bad, in den Konstruktor Injektion nicht funktioniert, ich habe vergessen, nur den Konstruktor Parameter an das Element var _env zuzuweisen. Später in der Invoke-Methode ist _env null. Hand gegen die Stirn! Es ist großartig zu erfahren, dass ich es in die Invoke-Methode einfügen kann. –

Antwort

6

Methode Injektion funktioniert, fügen Sie ihn einfach an die Methodensignatur

public async Task Invoke(HttpContext context, IHostingEnvironment env) {...}