ASP.NET MVC - How to access Session data in places other than Controller and Views

后端 未结 5 1234
粉色の甜心
粉色の甜心 2020-11-30 01:44

We can access session data in controllers and views like this:

Session[\"SessionKey1\"]

How do you access Session values from a class othe

5条回答
  •  Happy的楠姐
    2020-11-30 02:44

    I'd use dependency injection and pass the instance of the HttpContext (or just the session) to the class that needs access to the Session. The other alternative is to reference HttpContext.Current, but that will make it harder to test since it's a static object.

       public ActionResult MyAction()
       {
    
           var foo = new Foo( this.HttpContext );
           ...
       }
    
    
       public class Foo
       {
            private HttpContextBase Context { get; set; }
    
            public Foo( HttpContextBase context )
            {
                this.Context = context;
            }
    
            public void Bar()
            {
                var value = this.Context.Session["barKey"];
                ...
            }
       }
    

提交回复
热议问题