当我尝试从IHttpContextAccessor字段获取httpcontext时,我总是遇到问题。
有我的startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
.....
// This is always null
var httpContext = app.ApplicationServices.GetService<IHttpContextAccessor>().HttpContext;
.....
}
Configure
方法中始终会有空的HttpContext 。
此方法用于指定ASP.NET应用程序如何响应HTTP请求并在应用程序启动时调用一次,而不是针对每个HTTP请求。这就是为什么什么都没有,可以填充什么的原因HttpContext
。
您需要传递IHttpContextAccessor
服务类并IHttpContextAccessor.HttpContext
在请求处理期间致电。您可能会在此SO post中获得HTTP上下文来研究“类似”情况。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句