Question about the session in a c# web application
User LoginUser = new User(); Session["User"]开发者_如何学Python = LoginUser;
What does it mean to pass an object(LoginUser) to Session? Will the session get any time value from the object(LoginUser)?
You are adding the object to a session variable that will be then accessible throughout the application during that session.
You can then (in other pages, for example) access it like this:
User loginUser = (User)Session["User"];
You need to be careful when using loginUser
as if the session times out, or if you have not added the object to the session before hand, it may be null
.
You should note that the User object is serialized when you put it in the session of your app.
User LoginUser = new User();
It has some consequences: 1) the User class must be serializable.
2) When you will access the object later, (see Oded answer), it will be deserialized from the session: You won't keep the same reference.
User loginUser = new User();
loginUser.Name="user1";
Session["User"] = LoginUser;
loginUser.Name = "user2";
var loginUser2 = (User)Session["User"];
=> loginUser2.Nam contains "user1";
Why does it work this way? When you put an object in the session, the .NET framework will store it somewhere, (perhaps in server memory, in a file or in a DB depending upon the session storage mecanism). To persist your object, it will be serialized (transformed into a sequence of bytes). The serialization process is described in MSDN. The serialization process is quite parametrable, and the subject is quite large. Too large to be covered in this post in fact.
To make a serializable class, you can simply add the Serializable attribute to the class, and ensure that all the class fields or properties are serializables too.
[Serializable]
public class MyClass
{
public string Field{get,set}
}
精彩评论