Why Session is a disaster in ASP.NET MVC applicati

2019-01-13 07:54发布

问题:

Why is it being said We should not use Session variables in ASP.NET MVC applications ? I came across this answer which says so. In that case how will i maintain the values across requests like Logged in User information and some relevant data associated to his account?

This is Darin's answer.

Why are you using HttpContext.Current in an ASP.NET MVC application? Never use it. That's evil even in classic ASP.NET webforms applications but in ASP.NET MVC it's a disaster that takes all the fun out of this nice web framework.

回答1:

One of the fundamental principles of frameworks like ASP.NET MVC is that they are stateless, just like the Web is. ASP.NET Web Forms is an attempt to mimic a stateful paradigm over a stateless enviroment. It is a lie, in other words.

Using Session variable in an ASP.NET MVC application is a bit like tying a horn to a horse's head, and calling it a Unicorn.



回答2:

You can use session state to persist data, TempData functionality use Session as default to persist the data.

You should minimise the use of session as much as possible, the reason for that is that a lock is taken on session for all request to prevent corruption of the session state, for example multiple Ajax requests will serialise because of this. More information here

You can use alternatives to persist data between request for example you can use the CookieValueProvider, which is part of MVC Futures to bind cookie data to model. You can also persist data in the actual DOM as hidden fields, but again these should be minimised as much as possible as the size of the data will be reflected in network traffic to and from the browser.

I would consider using another data store for your web application if your main store is slow. For example SQLServer CE or an embedded RavenDB.