I've recently started working on a web app with a new company and found that the session object is used pretty much all the time to hold everything. Often it's used to pass data between pages instead of using the query string or ViewState.
Other times it's used it to cache datatables so they're not requested from the DB a second time.
Basically, any time data needs to be stored, a session is used.
This is pretty much the exact opposite of what I do. If it looks like a session variable is needed, I'll rethink my design, or maybe sacrifice some efficiency (i.e. reload the data from the databse, rather than store it in a session).
I'm actually thinking that we should always wrap our session objects as Singletons or something to ensure they're not overly used.
My argument is that Session items are really global variables, so if you find yourself using it to pass data around whenever you feel like it, you're making the page tightly coupled with other pages, bcause they rely on some other page setting开发者_运维问答 the value.
Also, you can never rely on the data coming through being correct, as another page may have changed it in the intrim, ie: Session["Id"] on one page might accidentally get overidden by a Session["Id"] in another browser tab.
There are actually lots of other reasons I think of as well, but can anyone confirm this for me?
Most sites/forums I've found recommend people use the session as much as they feel like, to store anything. I'd expect it would be discouraged.
Does anyone know of a best practice that's generally accepted?
Nothing is wrong with the session if you want to use it and use it in an effective manner. Just like any other technology it can be misused and its up to you to 'cleanly' use it a properly architected manner (ideally centralized session access as well)
You said: "My argument is that Session items are really global variables, so if you find yourself using it to pass data around whenever you feel like it, you're making the page tightly coupled with other pages, bcause they rely on some other page setting the value. "
Who said its only for page data? I would be more inclined to use it for session data - such as user specific information that maybe one doesn't want to serialize out to a forms auth ticket. Using the session in this case is actually better for performance as locking the collection is generally a less expensive operation than the ticket decryption that occurs.
Create a centralized place to use these values. If you need to use it to pass data between pages - then I would consider a better approach - such as posting or querystring or headers or other context information - or... etc etc.
Remember you can misuse almost anything in technology. Sessions can be used wisely and I've seen plenty of applications do it. It's up to you.
精彩评论