2013-05-16 13 views
7

Per qualche motivo, la proprietà UserData del mio cookie di autenticazione è vuota. Ecco il codice:La proprietà UserData di FormsAuthenticationTicket è vuota nonostante sia impostata

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

Ecco come provo per accedervi:

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

risposta

7

RedictFromLoginPage sovrascrive il cookie. Rimuovi questa linea e reindirizza manualmente (Response.Redirect).

+0

sto usando 'Response.Redirect' ma ancora' UserData' ha una stringa vuota – Ravi

+0

@Ravi: inserisci il tuo snippet di codice come domanda. –

+0

ho postato la mia domanda [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

Questa è una risposta simile che ho risposto pochi giorni fa.

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

Non è possibile utilizzare FormsAuthentication.SetAuthCookie o FormsAuthentication.RedirectFromLoginPage se si crea FormsAuthenticationTicket da soli.

+0

Ho capito che anche FormsAuthentication.GetRedirectUrl ha questo problema. Recupero dell'URL e memorizzazione in una variabile, quindi impostazione del cookie e infine reindirizzamento risolto il problema. –

0

mi sembra che stavi facendo lo stesso tutorial ... ho incontrato lo stesso problema nel mio caso .. è stato un errore di configurazione web ..

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

se avete cookieless = "UseUri" nella tua configurazione web rimuovilo .. funziona nel mio caso

Problemi correlati