2017-01-04 4 views
0

Это код, который я использую для хранения cookie после аутентификации пользователя.Как получить сохраненный файл cookie в mvc4?

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

https://msdn.microsoft.com/en-us/library/aa287533(VS.71).aspx – stuartd

ответ

2

Чтобы получить печенье:

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

Чтобы получить билет внутри печенья:

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

Типичный способ ведения it-- реализовать AuthenticateRequest в Global.asax.cs ... что-то как это ....

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

... тогда, когда любой из ваших кодов должен получить доступ к текущему пользователю, просто получите c КОНТЕКСТ пользователь:

var user = HttpContext.Current.User; 

Link

Смежные вопросы