如何在中间件中访问 IHostingEnvironment class
How to access IHostingEnvironment in middleware class
在 Asp.Net 核心中,如果创建了一个自定义的中间件并将其放置在它自己的 class 中,如何从中间件内部访问 IHostingEnvironment
?
例如,在下面的 class 中,我认为我可以将 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) {...}
在 Asp.Net 核心中,如果创建了一个自定义的中间件并将其放置在它自己的 class 中,如何从中间件内部访问 IHostingEnvironment
?
例如,在下面的 class 中,我认为我可以将 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) {...}