gpt4 book ai didi

asp.net-core - 如何在中间件类中访问 IHostingEnvironment

转载 作者:行者123 更新时间:2023-12-04 13:37:11 53 4
gpt4 key购买 nike

在 Asp.Net Core 中,如果创建了一个自定义中间件并将其放置在它自己的类中,如何访问 IHostingEnvironment从中间件内部?

例如,在我下面的类(class)中,我认为我可以注入(inject) 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);

}
}

最佳答案

方法注入(inject)有效,只需将其添加到方法签名中

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

关于asp.net-core - 如何在中间件类中访问 IHostingEnvironment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41108099/

53 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com