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..

1

2 Answers 2

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;

Sign up to request clarification or add additional context in comments.

4 Comments

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?
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.
What's the advantage in writing a wrapper to access session
you have a single entry point. Ease of maintaining. Intellisense
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.

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.