且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在ASP.NET Core中访问当前的HttpContext

更新时间:2023-02-16 09:13:00

HttpContext.Current在ASP.NET Core中不再存在,但是有一个新的

HttpContext.Current doesn't exist anymore in ASP.NET Core but there's a new IHttpContextAccessor that you can inject in your dependencies and use to retrieve the current HttpContext:

public class MyComponent : IMyComponent
{
    private readonly IHttpContextAccessor _contextAccessor;

    public MyComponent(IHttpContextAccessor contextAccessor)
    {
        _contextAccessor = contextAccessor;
    }

    public string GetDataFromSession()
    {
        return _contextAccessor.HttpContext.Session.GetString(*KEY*);
    }
}