Asp.net-Core
如何在中間件類中訪問 IHostingEnvironment
在 Asp.Net Core 中,如果創建了一個自定義中間件並將其放置在它自己的類中,如何
IHostingEnvironment從中間件內部訪問?例如,在我下面的課程中,我認為我可以注入
IHostingEnvironment建構子,但它始終為空。關於如何訪問的任何其他想法IHostingEnvironment?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); } }
方法注入有效,只需將其添加到方法簽名中
public async Task Invoke(HttpContext context, IHostingEnvironment env) {...}