How to Persist data using session variable in mvc3 razor view?

这一生的挚爱 提交于 2019-12-04 05:09:54

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;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!