1

Hello I am looking to use a session variable in MVC 3 C# to store a user Id, so that the user doesn't have to enter their user id on create form

Where should I put the code for the session variable, if not in the global.asax file? i know the code looks something like

    Session["userId"]

I have seen examples using the global.asax but it is very confusing.

Thank you in advance

  • 2
    Presumably you have some kind of login process? You would normally associate a userid with some opaque token (i.e. the user's auth cookie) at *that* point...? – Marc Gravell Aug 30 '11 at 09:46
  • 2
    possible duplicate of [Session variables in ASP.NET MVC](http://stackoverflow.com/questions/560084/session-variables-in-asp-net-mvc) – Oded Aug 30 '11 at 09:52
  • You might consider putting the id in the Forms authentication ticket and creating a custom `IIdentity` that has an Id property on it. Usually though, you would identify a user via the `Name` property on the `IIdentity` (which is what Membership providers do) – Russ Cam Aug 30 '11 at 09:54
  • This has already been answered here: http://stackoverflow.com/questions/560084/session-variables-in-asp-net-mvc I hope it helps, happy coding! – Hiral Desai Aug 30 '11 at 09:51
  • @Hiral an "answer" that consists **only** of a link to another stackoverflow post is not really an answer; either a "close as duplicate" vote or a comment is usually more appropriate – Marc Gravell Aug 30 '11 at 09:58
  • Thanks Marc, will keep that in mind next time. :-) – Hiral Desai Aug 30 '11 at 10:03

2 Answers2

0

You can access the Session object in your controllers.

Whether you should is a different question - depending on Session will make your code difficult to test.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • I'd go further and say that session is always evil. – kmcc049 Aug 30 '11 at 09:46
  • I'm not sure whether I agree that it makes it any more difficult to test since Session property on a controller is of type `HttpSessionStateBase` which is easy to fake. It is an additional dependency for sure though. – Russ Cam Aug 30 '11 at 09:51
  • Whether session is evil or not, explain to me how to build a login banking enterprise website that needs to be 508 compliant and degrade gracefully thus not relying on javascript or cookies that doesn't use sessions. I am not seeing another option when the requirements are to popup warnings at 15 minutes and log person out at 20 minutes. – Tom Stickel Sep 05 '11 at 01:11
0

If you are planning on using that later on in a few places, a good place to put that in place is in the login part so that you know if a user is logged in the session varaibale is set. You can then access it from any controller if the user is logged in

kmcc049
  • 2,783
  • 17
  • 13