Ron*_*n C 6 asp.net-core-mvc asp.net-core asp.net-core-1.0
在Asp.Net Core中,如果创建了一个自定义的中间件并将其放置在自己的类中,那么如何IHostingEnvironment从中间件内部访问?
例如,在我下面的课程中,我认为我可以注入IHostingEnvironmentcontstructor,但它始终为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);
}
}
Run Code Online (Sandbox Code Playgroud)
Joe*_*tte 12
方法注入工作,只需将其添加到方法签名
public async Task Invoke(HttpContext context, IHostingEnvironment env) {...}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2147 次 |
| 最近记录: |