官网关于HttpContext使用说明
参考:通过自定义组件使用 HttpContext
https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/http-context?view=aspnetcore-2.2
在控制器中直接使用HttpContext为null
- 控制器直接可以访问HttpContext
- 父类访问HttpContext为null
解决父类访问不到HttpContext
- 新建类(HelperHttpContext.cs),编辑内容如下(需要添加引用)
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace L.UtilityTool.Helper
{
public static class HelperHttpContext
{
public static IServiceCollection serviceCollection;
public static HttpContext Current
{
get
{
object factory = serviceCollection.BuildServiceProvider().GetService(typeof(IHttpContextAccessor));
HttpContext context = ((IHttpContextAccessor)factory).HttpContext;
return context;
}
}
}
}
- 在StartUp.cs中增加如下代码
// 增加Http组件
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
HelperHttpContext.serviceCollection = services;
- 验证父类HttpContext
- 使用方式 HelperHttpContext.Current