7

I am working in MVC3 Application with Razor. In my Account controller after validating the user, i am getting the user ClientID from Database. Here i want to persist ClientID in Session variable. which was using across the all controller and Razor view.

I have no idea as to what is the best way to implement this.OR How to persist data in the session variable. And how to use persisted data in the session variable in across the controller.

Thanks for your help..

user10489
  • 255
  • 2
  • 6
  • 17
  • This could be useful http://www.hanselman.com/blog/TroubleshootingExpiredASPNETSessionStateAndYourOptions.aspx – ManirajSS Feb 14 '15 at 06:57

2 Answers2

19

I usually write a Session wrapper that allows me easy access to it in the future:

public class SessionData
{
    const string ClientId_KEY = "ClientId";

    public static int ClientId
    {
        get { return HttpContext.Current.Session[ClientId_KEY] != null ? (int)HttpContext.Current.Session[ClientId_KEY] : 0; }
        set { HttpContext.Current.Session[ClientId_KEY] = value; }
    }
}

After that you can access it from anywhere like this:

int clientId = SessionData.ClientId;

If you want you can use whole objects in Session like this.

Or you can set it like so: SessionData.ClientId = clientId;

Dmitry Efimenko
  • 10,973
  • 7
  • 62
  • 79
  • Thanks for your response...Basically we are implementing Multi Tenant access for our framework. So the Session is good approach? And i am getting the ClientID based on logged user from DB. so how can i bind CliendID in to Session variable? – user10489 Jul 25 '12 at 07:06
  • I cannot know all the implications and requirements of your project, but so far I don't see any problems using Session. I've updated my answer to show how you can set ClientId in Session using the wrapper. – Dmitry Efimenko Jul 25 '12 at 07:25
  • What's the advantage in writing a wrapper to access session – Nipuna Jul 12 '15 at 04:30
  • you have a single entry point. Ease of maintaining. Intellisense – Dmitry Efimenko Jul 13 '15 at 00:06
2

If you are using ASP.NET Forms Authentication, the user name is already stored in a cookie. You can access it from the Controller via

Controller.User.Identity.Name

It's possible to store the user ID as the user name. When you call something like

FormsAuthentication.RedirectFromLoginPage

Give it the ID instead of a name. The ID can then be found using the method above and no extra session data is necessary. If you want to store something in the session, just call

Session["UserID"] = value;

From your controller.

BC.
  • 24,298
  • 12
  • 47
  • 62
  • Thanks for your response.. Actually we are implementing Multi Tenant access for our Framework. So i am bit confused about persisting data across the controller. so can you suggesting me which one is better approach? – user10489 Jul 25 '12 at 07:17