Using Session objects in MVC, Is it really bad?

2019-01-26 14:36发布

问题:

I am proposing to use a simple session object in a MVC3 to maintain state data like RecordIds rather than pass them through all the client side pages which will be a hassle. It seems far simpler to just populate the session object the once until no longer in use.

So is this acceptable practice or a cheat??

Many thanks.

回答1:

There's nothing wrong with using Session objects. Generally people avoid them to reduce the load on the server; but if you're careful and don't try to put lots of data in there and don't have too many (how many is too many depends on your server) then it is an acceptable practice.

For some info on the potential drawbacks of using sessions check out the answer to Still ok to use Session variables in ASP.NET mvc, or is there a better alternative for some things (like a cart)



回答2:

Like everything in developer's life, using session is a trade-off, and a IMHO it is usually a bad one.

Session state not only causes load on server that tends to grow and creates scalability barrier (both problems can be - partially - solved with storing session variables with state server or sql server), it has a by-design quirk that not everybody is aware of: It maintains a read-write lock on the session. (http://msdn.microsoft.com/en-us/library/ms178581(v=vs.100).aspx)

This means that by default, no two concurrent request can be made by the same user. This behavior is asp.net related (not just asp.net MVC), however since asp.net MVC really encourages you to go down the ajax road, you will see this problem much more often).

You can bypass these problems by smartly using readonly session state or selectively disabling it, but from my experience that creates development overhead, since that attribute can only be declared on class scope, and not for specific action methods, which leads you to break apart logical units that would normally lie together.

In conclusion, your honor, asp.net session state default behavior is problematic. Avoid using it if possible.