2011-12-13 1 views
25

Sto creando un cookie e memorizzando il valore del nome utente dopo il login riuscito. Come posso accedere al cookie quando il sito è aperto. Se il cookie esiste, voglio riempire la casella di testo del nome utente dal valore del cookie. E come decifrare il valore per ottenere il nome utente. Sto facendo la convalida lato server ottenendo i dettagli utente dal database. Sto usando vs 2010 con C#Come ottenere il valore del cookie nel sito Web asp.net

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

cookie viene creato con nome come .YAFNET_Authentication e il contenuto è crittografato

Webconfig:

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

risposta

57

È possibile utilizzare Request.Cookies raccolta per leggere i cookie.

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

FormsAuthentication.Decrypt assume il valore effettivo del cookie, non il nome di essa. È possibile ottenere il valore del cookie come

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

e decrittarlo.

7

aggiungere questa funzione al vostro 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; 
} 

quindi è possibile utilizzare HttpContext.Current.User.Identity.Name per ottenere nome utente. Spero che aiuta

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

Riferimento Click here