2013-05-16 31 views
7

Vì một số lý do, tôi thuộc tính UserData của cookie xác thực của tôi trống. Đây là mã:Thuộc tính UserData của FormsAuthenticationTicket trống mặc dù được đặt

var authCookie = FormsAuthentication.GetAuthCookie(userName, rememberUser.Checked); 
// Get the FormsAuthenticationTicket out of the encrypted cookie 
var ticket = FormsAuthentication.Decrypt(authCookie.Value); 
// Create a new FormsAuthenticationTicket that includes our custom User Data 
var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, "userData"); 
// Update the authCookie's Value to use the encrypted version of newTicket 
authCookie.Value = FormsAuthentication.Encrypt(newTicket); 
// Manually add the authCookie to the Cookies collection 
Response.Cookies.Add(authCookie); 
FormsAuthentication.RedirectFromLoginPage(userName, rememberUser.Checked); 

đây là làm thế nào tôi cố gắng truy cập vào nó:

if (HttpContext.Current.Request.IsAuthenticated) 
{ 
    var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; 
    if (authCookie != null) 
    { 
     var authTicket = FormsAuthentication.Decrypt(authCookie.Value); 
     string data = authTicket.UserData; 
     // data is empty !!! 
    } 
} 

Trả lời

7

RedictFromLoginPage ghi đè cookie của bạn. Xóa dòng này và chuyển hướng thủ công (Response.Redirect).

+0

tôi đang sử dụng 'Response.Redirect' nhưng vẫn' UserData' có chuỗi rỗng – Ravi

+0

@Ravi: đăng đoạn mã của bạn dưới dạng câu hỏi. –

+0

tôi đã đăng câu hỏi của mình [http://stackoverflow.com/questions/20816425/getting-formsauthentication-ticket-userdata-as-empty-string](http://stackoverflow.com/questions/20816425/getting-formsauthentication- ticket-userdata-as-empty-string) – Ravi

3

Đây là câu trả lời tương tự mà tôi đã trả lời vài ngày trước.

https://stackoverflow.com/a/16365000/296861

Bạn không thể sử dụng FormsAuthentication.SetAuthCookie hoặc FormsAuthentication.RedirectFromLoginPage nếu bạn tạo FormsAuthenticationTicket một mình.

+0

Tôi nhận ra rằng FormsAuthentication.GetRedirectUrl cũng có vấn đề này. Truy xuất url và lưu trữ vào một biến, sau đó thiết lập cookie và cuối cùng làm chuyển hướng đã giải quyết được vấn đề. –

0

có vẻ như với tôi bạn đang làm cùng hướng dẫn ... tôi đã gặp phải cùng một vấn đề trong trường hợp của tôi .. đó là một lỗi web cấu hình ..

<authentication mode="Forms"> 
    <forms slidingExpiration="true" timeout="60" cookieless="UseUri"/> 
    </authentication> 

nếu bạn có cookie = "UseUri" trong cấu hình web của bạn xóa nó .. nó hoạt động trong trường hợp của tôi

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