Context.Session in a Class outside Controller

前端 未结 1 1262
悲哀的现实
悲哀的现实 2021-01-13 14:22

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

相关标签:
1条回答
  • 2021-01-13 15:12

    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*);
        }
    }
    
    0 讨论(0)
提交回复
热议问题