Asp.net - Do changes to session objects persist?

后端 未结 4 1029
半阙折子戏
半阙折子戏 2021-01-18 06:06

I\'m using the session to hold a custom object UserSession and I access the session like this:

UserSession TheSession = HttpContext.Current.Session[\"UserSes         


        
相关标签:
4条回答
  • 2021-01-18 06:51

    The standard session provider is a simple dictionary that stores objects in memory.

    You're modifying the same object that you put in the session, so the modifications will persist.
    (unless you're using an evil mutable struct)

    0 讨论(0)
  • 2021-01-18 06:57

    Yes it is the same object. It is very easy to see in the following example:

    Session["YourObject"] = yourObject;
    yourObject.SomeProperty = "Test";
    var objectFromSession = (YourObjectType)(Session["YourObject"]);
    Response.Write(objectFromSession.SomeProperty);
    

    The Write will display: Test

    0 讨论(0)
  • 2021-01-18 07:02

    It doesn't need to reassign the object. Because both of them are pointing to same instance in memory

    0 讨论(0)
  • 2021-01-18 07:07

    create a static class with static properties:

    public static class UserSession
    {
        public static int UserID
        {
             get { return Convert.ToInt32(Session["userID"]); }
             set { Session["userID"] = value; }
        }
    }
    

    When u use it:

    UserSession.UserID = 23;
    Response.Write(UserSession.UserID);
    

    it will use the session variable to store information passed to this property.

    0 讨论(0)
提交回复
热议问题