Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Context.Session in a Class outside Controller

In the controller I'm currently using Context.Session.GetString(*KEY*);
I have a class that needs to read from a few values stored in the session

I used to use this HttpContext.Current.Session[*KEY*].

I've tried searching in Stackoverflow and MSDN with no luck.

like image 381
Jordan Coulam Avatar asked Dec 25 '22 17:12

Jordan Coulam


1 Answers

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: https://github.com/aspnet/Hosting/blob/dev/src/Microsoft.AspNet.Hosting.Abstractions/IHttpContextAccessor.cs

public class MyComponent : IMyComponent {
    private readonly IHttpContextAccessor contextAccessor;

    public MyComponent(IHttpContextAccessor contextAccessor) {
        this.contextAccessor = contextAccessor;
    }

    public string GetDataFromSession() {
        return contextAccessor.HttpContext.Session.GetString(*KEY*);
    }
}
like image 138
Kévin Chalet Avatar answered Jan 05 '23 10:01

Kévin Chalet