Sessions and storing objects
If return an object from the session (HttpContext.Current.Session) to a private member of the objects type and then modify it, e.g. you rename an attribute or add something to the objects internal list member. Are those changes persisted if on another page you request the same object from the session...will it be updated with the values updated on the previous page. In other words is t开发者_如何学编程he object persisted, or do you have to re-save the object back to the session once you change anything on every page. Any help is much appreciated. Thanks
If it is an actual object then yes, you are modifying the version that is maintained by session and it's values will be saved.
If it is not a reference type, like String, then you have to reference the actual session value to modify it (ie: session["key"] = value).
However, I would caution you against storing real objects in session. Session works by serializing and deserializing the values on every single page load. The more you put into session the more work the framework has to perform before even beginning to execute your page.
Because of how it works you really should only put values in session that you truly need across the entire site.
Before even considering putting something in session I ask myself the following:
- Is this something needed for the entire site or close to it?
- Is the time to load this information straight from the database on an as needed basis more than pulling it from the web servers memory?
- Is this site load balanced or has the potential of being load balanced in the future?
If 1 is yes, then using session is a "maybe"
If 2 is yes, then session is also a maybe, but I'd probably use a different caching mechanism.
If 3 is a yes then I don't use session at all (and completely turn it off). Load balancing requires a session state server, which is usually a sql server. Which leads us back to the initial problem with session: namely, the values are loaded and saved for every single page request.
If you modify an instance which is stored in session state, the instance will be modified.
If you modify a copy of an instance, the original will not be affected. (unless the copy references the original and updates it, which is unlikely)
Although you could have tested this for yourself very easily, the answer is yes - the object will be persisted!
The objects stored in the Session dictionary are stored by reference so what this means is that if you change the object's internal properties or structure (i.e. if you store a List<> object and add or remove items) those changes will be preserved.
That being said, if you store a value type such as an Int32 or a Boolean, then if you change the value you need to specifically set it to the Session.
精彩评论