在Asp.Net Core中,如果创建了一个自定义的中间件并将其置于其自己的类中,那么如何从中间件内部访问IHostingEnvironment
?
例如,在我下面的课程中,我认为我可以将IHostingEnvironment
注入到contstructor中,但它始终为null。关于如何访问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);
}
}
答案 0 :(得分:11)
方法注入工作,只需将其添加到方法签名
public async Task Invoke(HttpContext context, IHostingEnvironment env) {...}