maxswitcher maxswitcher - 1 month ago 19
C# Question

Access HttpContext.Current

I need to access current

HttpContext
in static method.

With
System.Web
i just use
HttpContext.Current
, how to do this in ASP.NET vNext?

Answer

HttpContext.Current doesn't exist anymore in ASP.NET 5, 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) {
        this.contextAccessor = contextAccessor;
    }

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