HttpContext.Current在ASP.NET Core中不再存在,但是IHttpContextAccessor可以在依赖关系中注入一个新的并用于检索当前HttpContext
1、注册服务
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
2、使用
public class MyComponent : IMyComponent { private readonly IHttpContextAccessor _contextAccessor; public MyComponent(IHttpContextAccessor contextAccessor) { _contextAccessor = contextAccessor; } public string GetDataFromSession() { return _contextAccessor.HttpContext.Session.GetString(*KEY*); } }