2017-01-04 10 views
0

これは、ユーザーが認証された後に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を取得するには、次に何をすればよいですか?クッキー内のチケットを取得するには

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

:クッキーを取得するには

+1

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

答えて

2

global.asax.csでたAuthenticateRequestを実装it--を行う

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

典型的な方法を...何かあなたのコードのいずれかが現在のユーザーにアクセスする必要があるたびに、このように....

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を得ますontextユーザー:

var user = HttpContext.Current.User; 

Link

関連する問題