首先不推荐这样做,仅限无奈需要这样做的时候,再这样做。。。
参考:https://www.cnblogs.com/maxzhang1985/p/6186455.html
https://www.cnblogs.com/linezero/p/6801602.html
public static class HttpContextStatic { public static IServiceProvider ServiceProvider; public static void Configure(IServiceProvider serviceProvider) { ServiceProvider = serviceProvider; } public static HttpContext Current { get { var factory = ServiceProvider.GetService(typeof(IHttpContextAccessor)); var accessor = (HttpContextAccessor) factory; return accessor?.HttpContext; } } }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { HttpContextStatic.Configure(app.ApplicationServices); }