如何在mvc4中检索存储的cookie?

时间:2017-01-04 09:38:16

标签: c# asp.net-mvc cookies

这是我在用户通过身份验证后用于存储Cookie的代码。

var authTicket = new FormsAuthenticationTicket(
    1,
    Session["UserID"].ToString(),  //user id
    DateTime.Now,
    DateTime.Now.AddDays(1),  // expiry
    true,  //true to remember
    "", //roles 
    "/"
);

HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
if (authTicket.IsPersistent) { cookie.Expires = authTicket.Expiration; }
Response.Cookies.Add(cookie);

当用户再次访问该网站时,我该怎么做才能检索此Cookie?

1 个答案:

答案 0 :(得分:1)

获取cookie:

HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];

要在cookie中获取票证:

FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

这样做的典型方式 - 在global.asax.cs中实现AuthenticateRequest ......就像这样....

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
    if (authCookie != null)
    {
        // Get the forms authentication ticket.
        FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
        var identity = new GenericIdentity(authTicket.Name, "Forms");
        var principal = new MyPrincipal(identity);

        // Get the custom user data encrypted in the ticket.
        string userData = ((FormsIdentity)(Context.User.Identity)).Ticket.UserData;
        // Deserialize the json data and set it on the custom principal.
        var serializer = new JavaScriptSerializer();
        principal.User = (User)serializer.Deserialize(userData, typeof(User));
        // Set the context user.
        Context.User = principal;
    }
}

...然后,只要您的任何代码需要访问当前用户,只需获取上下文用户:

var user = HttpContext.Current.User;

Link