2013-05-16 45 views
7

由於某種原因,我的身份驗證Cookie的UserData屬性爲空。下面是代碼:儘管設置了FormsAuthenticationTicket的UserData屬性爲空

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

這裏是我嘗試訪問它:

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 !!! 
    } 
} 

回答

7

RedictFromLoginPage覆蓋您的Cookie。刪除此行並手動重定向(Response.Redirect)。

+0

我使用'Response.Redirect',但仍然'UserData'空字符串 – Ravi

+0

@Ravi:張貼您的代碼片段作爲一個問題。 –

+0

我發佈了我的問題[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

這是我幾天前回答的類似答案。

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

不能使用FormsAuthentication.SetAuthCookieFormsAuthentication.RedirectFromLoginPage,如果你自己創建的FormsAuthenticationTicket

+0

我意識到FormsAuthentication.GetRedirectUrl也有這個問題。檢索url並將其存儲到變量中,然後設置cookie並最後執行重定向來解決問題。 –

0

在我看來,你在做同樣的教程... 我在我的情況下,遇到同樣的問題 ..這是一個網絡配置錯誤..

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

,如果您有cookie的= 「UseUri」在你的網頁配置刪除它.. 它在我的情況下工作

相關問題