42

It's not explicitly written somewhere but I felt so after reading few blogs on ASP.NET MVC. Just got curious and thought of asking it here.

UPDATE:
I'm not asking about memory/storage/RAM concerns on server. For them, there is a solution to store session out of process. I know that. I'm curious that, are there any scenarios where we had to use Session in WebForms but we can avoid it now in MVC taking benefit of the nice structured way offered by MVC?

IsmailS
  • 10,797
  • 21
  • 82
  • 134

8 Answers8

45

In ASP.NET Web Forms, passing information between different pages was never especially easy without the use of session. Due to the postback-centric model, information was available on the server as part of an event, but often in the wrong page for displaying a result, making passing information between pages necessary.

This tended to lead to an overuse of session, populating "current" variables in session intended to indicate what the current object being interacted with was. This overuse in turn made applications very state-dependent and much harder to determine expected behaviour ("Is this variable populated?" "Do I have the current order ID yet?").

MVC is structured around the idea that your website is a view into a logical model of information. It encourages having stateless operations through the use of simple controllers responding to actions with key information passed as part of the HTTP request.

Because of these properties, session is no longer required to perform basic tasks in MVC, and becomes poor fit where it has seemed a perfectly valid choice before.


Fundamentally, session pollutes HTTP. It makes requests (often containing their own state) dependent on the internal state of the receiving server. This is why it's seen as something of an evil (although often a practical and necessary one).

Paul Turner
  • 38,949
  • 15
  • 102
  • 166
  • 5
    I think part of the reason for keeping "current" variables in the session is to avoid roundtrips to the database to re-fetch the data. But like you said, sometimes it's overused (and unnecessarily too). – Tundey Mar 07 '11 at 15:40
  • 1
    +1 Best answer till now. Good example mentioned where we had to use Session in web forms but now we don't in MVC. – IsmailS Mar 08 '11 at 06:57
  • If I have to store logged in user's Id, is there any other option than session. Because I see in NerdDinner sample that they have verified by `User.Identity.Name` which can be similar for two users. So is there any other way than `Session` which I can use for it? – IsmailS Mar 08 '11 at 09:57
  • 2
    The user's ID is a contextual information. If you don't want to use session, you could supply this as part of HTTP requests (a custom header for example). However, I'd say that user-context information is appropriate to be stored in session; if your session expires, the user must log in again anyway. – Paul Turner Mar 08 '11 at 10:34
  • If I store it in http header, some malicious user might try to modify it and access other user's information. Right? So that means, session is the best place for it. – IsmailS Mar 08 '11 at 10:55
  • 3
    Security is a consideration with whether to use session variables or not; they're always on the server and you don't have to worry about them being intercepted in transmission. But that isn't to say they're the only solution, as there are numerous ways to secure part or all of a HTTP request, techniques you will want to consider for the other elements of your HTTP requests. – Paul Turner Mar 08 '11 at 11:31
  • 2
    Sign-In cookies provide the User.Identity, and they are encrypted. With Identity 2.0 I know you can even control how they are encrypted and you would definitely do this in a web-farm situation. Cookies are sent by the client with every request so its something you should always have. No need to use session. Stateless means the client provides ALL the information required to process the request with the request. This allows any server in your farm to independently process it and return you a valid response. – Ian Robertson Jun 22 '15 at 12:29
  • Session state is not completely useless. Any system you make eventually has to maintain some state and for different users that would be different. Depending on the size of data, sending it to client and expecting it to send that back with every request is far worse than storing it in session or hitting database base on every request for that. – Simple Fellow Oct 06 '17 at 13:48
17

Session was avoided even before MVC, because it's info that gets persisted on the server for each of the users that connect to your application and (unlike cache) is not erased automatically when not used.

Also in order to help you avoid using session, ASP.NET had viewstate, which was actually a huge hidden field in your webforms that got POSTed on every postback. This too was too clumsy for various reasons and was dropped with MVC.

So session is actually something that was not very recommended even before MVC. The reason is mostly scalability. The less state you persist, the more scalable your site will be. If you don't care about scalability (for what I know you might be developing an intranet application for 200 users) or if you have very little info to persist by all means do use session. In other cases, using session is entirely appropriate: a typical scenario where session state is used is the shopping cart in a ecommerce site (info which is inherently per-user per-session and that only a percentage of your users actually have populated).

As for the alternatives,there is not a direct, drop-in replacement for session. Depending on what you're trying to do you may be able to use cache or cookies. MVC has not brought anything particularly new in that regard, AFAIK.

Paolo Falabella
  • 24,914
  • 3
  • 72
  • 86
  • and what is the alternative in MVC? – Ken D Mar 07 '11 at 14:56
  • 2
    @LordCover sorry, re-reading my answer I was too dogmatic. Session is not something that should be avoided under any circumstance and there may well be cases when using it is entirely appropriate. It's just that the more you can design your web application to avoid maintaining state, the more scalable it will be. That said, the alternatives depend on what kind of data you're trying to persist and why. – Paolo Falabella Mar 07 '11 at 15:01
  • Didn't think your answer was overly dogmatic. I think it was just evolution. Memory used to be rare and expensive and so in-memory server session was impractical. Then hardware and memory got cheap and web applications showed up and session was an idea that seemed good at the time and was widely used and unfortunately abused. People found scaling problems and now we're back to the beginning. I still see session being used for interesting stuff like complex graphical web apps and also for holding resources like TCP connections that can't be serialized. – nothingisnecessary Apr 30 '16 at 10:18
6

What would it mean to avoid using Session State for you? Do you need to conveniently store small amounts of user data across requests? If so, how else would you do it?

I'm not sure what your alternatives to Session State would be. Using Session State as it exists, out of the box, in ASP.NET is far more desirable to rolling your own alternative, especially from a security perspective.

Josh Pearce
  • 3,399
  • 1
  • 23
  • 24
6

Use TempData instead of HttpSessionState. TempData is Mvc's wrapper of Session state.

smartcaveman
  • 41,281
  • 29
  • 127
  • 212
  • I think TempData works best for redirects. That's the only time you can be sure of where the code is going. – DOK Oct 01 '12 at 13:42
  • 1
    Great comparison of options in MVC from Rachel Appel's blog: http://www.rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications I ended up using `TempData` as you suggested. – atconway Jan 31 '14 at 14:50
3

Adding to previous answers

Session are usually evil in terms of modern application and modern application here applies mostly to cloud-centric applications but hugely depends on where we store them.

Regardless of ASP.NET WebForms or ASP.NET MVC, usually with session, we imagine a shopping cart with cart filled or removed which is maintained throughout how actually session is maintained. So this was easy and cheap way of doing things, usually session resides on

  1. InProc
  2. StateServer
  3. SQLServer
  4. Now on distributed cache more details

HTTP by birth is stateless, so when we want to horizontally scale up application we add nodes to web-tier or other tiers, so now problem is which node will serve current user's request? it hugely depends on load-balancer which has different modes of doing balancing.

So multiple nodes can serve request for same user depending on loadbalancer but we can kind of override with sticky session in web-tier which will ensure current user will use same nodes, that fails when scaling up application, classic example consider we have 1,000 active session on each 2 node and now we add one more node, we generally expect 3 nodes share near equal number of session however that fails coz those 1,000 must be active in particular nodes cause we are using sticky session, scaling will take time till those session are cleared.

Again what if we want to scale up or reverse scale application? or one or more server goes down, whole session data will be lost if we keep session on InProc or StateServer and even when web-tier nodes switches for same user, whereas if we store on SQLServer its fine but usually slow, so the answer here seems to be distributed cache which is fast and can be made reliable.

Sandip Bantawa
  • 2,822
  • 4
  • 31
  • 47
2

Session expiration usually doesn't correspond to user's intention (e.g, if IIS recycles, your inproc session state is lost). The only thing I think it may be useful for is user data caching, and not the authoritative source of truth (which most probably should be DB).

driushkin
  • 3,531
  • 1
  • 24
  • 25
1

It really depends on how much data you are maintaining in the session state. As a rule of thumb, I try to just use it for a few strings here and there and not much more. For a large form, for example, I might store a reference ID to that session, then store all the needed data in SQL temp tables based on that ID. It is kind of a pain, but the session state is not meant to be used to store loads of information.

Morgan Herlocker
  • 1,498
  • 4
  • 24
  • 42
  • 1
    I think the straight forward answer to your questions is: No. Just follow best practices for MVC. I think any MVC anti-session-state rhetoric you encounter would be aimed at developers who are bringing bad habits and an over-dependence-on-session-state type baggage to the table. – Josh Pearce Mar 07 '11 at 15:21
0

Session management was always challenging from ASP.net Web Forms to ASP.net MVC. However, MVC encourages to treate it as Stateless as you have benefit of REST based Web API. Most of the things that we used to store in Session previously accomplished by using both MVC + Web API combination.

marvelTracker
  • 4,691
  • 3
  • 37
  • 49
  • I think when the question was asked, Web API was in too early stages. May be not even in beta phase. – IsmailS Jan 19 '16 at 08:39