2011-12-13 72 views
25

我正在創建cookie並在成功登錄後存儲用戶名的值。如何在打開網站時訪問cookie。如果存在cookie,我想填充cookie值中的用戶名文本框。以及如何解密值以獲取用戶名。我通過從數據庫獲取用戶摘要來進行服務器端驗證。我使用VS 2010的C#如何在asp.net網站上獲取cookie值

FormsAuthenticationTicket tkt; 
string cookiestr; 
HttpCookie ck; 
tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now, 
    DateTime.Now.AddYears(1), chk_Rememberme.Checked, "User Email"); 
cookiestr = FormsAuthentication.Encrypt(tkt); 
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr); 

if (chk_Rememberme.Checked) 
{ 
    ck.Expires = tkt.Expiration; 
    ck.Path = FormsAuthentication.FormsCookiePath; 
    Response.Cookies.Add(ck); 
} 

餅乾與名稱創建爲.YAFNET_Authentication和內容加密

Webconfig:

<forms name=".YAFNET_Authentication" loginUrl="Home.aspx" 
    protection="All" timeout="15000" cookieless="UseCookies"/> 

回答

57

您可以使用Request.Cookies收集閱讀餅乾。

if(Request.Cookies["key"]!=null) 
{ 
    var value=Request.Cookies["key"].Value; 
} 
13

FormsAuthentication.Decrypt獲取cookie的實際值,而不是它的名稱。你可以得到的cookie值如

HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value; 

並解密。

7

此功能添加到您的Global.asax

protected void Application_AuthenticateRequest(Object sender, EventArgs e) 
{ 
    string cookieName = FormsAuthentication.FormsCookieName; 
    HttpCookie authCookie = Context.Request.Cookies[cookieName]; 

    if (authCookie == null) 
    { 
     return; 
    } 
    FormsAuthenticationTicket authTicket = null; 
    try 
    { 
     authTicket = FormsAuthentication.Decrypt(authCookie.Value); 
    } 
    catch 
    { 
     return; 
    } 
    if (authTicket == null) 
    { 
     return; 
    } 
    string[] roles = authTicket.UserData.Split(new char[] { '|' }); 
    FormsIdentity id = new FormsIdentity(authTicket); 
    GenericPrincipal principal = new GenericPrincipal(id, roles); 

    Context.User = principal; 
} 

那麼你可以使用HttpContext.Current.User.Identity.Name獲取用戶名。希望它可以幫助

0
HttpCookie cook = new HttpCookie("testcook"); 
cook = Request.Cookies["CookName"]; 
if (cook != null) 
{ 
    lbl_cookie_value.Text = cook.Value; 
} 
else 
{ 
    lbl_cookie_value.Text = "Empty value"; 
} 

參考Click here