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