2011-12-13 91 views
25

Tôi đang tạo cookie và lưu trữ giá trị của tên người dùng sau khi đăng nhập thành công. Làm thế nào tôi có thể truy cập cookie khi trang web được mở. Nếu cookie tồn tại tôi muốn điền vào hộp văn bản tên người dùng từ giá trị cookie. Và cách giải mã giá trị để lấy tên người dùng. Tôi đang thực hiện xác thực phía máy chủ bằng cách lấy các userdetails từ cơ sở dữ liệu. Tôi đang sử dụng vs 2010 với C#Cách lấy giá trị cookie trong trang 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 được tạo ra với tên như .YAFNET_Authentication và nội dung được mã hóa

webconfig:

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

Trả lời

57

Bạn có thể sử dụng bộ sưu tập Request.Cookies để đọc các tập tin cookie.

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

FormsAuthentication.Decrypt lấy giá trị thực của cookie chứ không phải tên của nó. Bạn có thể nhận được giá trị cookie như

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

và giải mã điều đó.

7

thêm chức năng này để 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; 
} 

của bạn sau đó bạn có thể sử dụng HttpContext.Current.User.Identity.Name để có được tên người dùng. hy vọng nó sẽ giúp

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

Reference Click here

Các vấn đề liên quan