36
votes

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.

2
I didn't say that you should not use Session (actually I said it and I am saying it right now but not in the answer you linked to). I said that you should not use HttpContext.Current to access the current HTTP context.Darin Dimitrov
Here is an article that explains one reason why using HttpContext.Current is a bad idea - basically it is not thread safe: odetocode.com/articles/112.aspxJTech

2 Answers

28
votes

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.

7
votes

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.