在.NET 3.5中回发后,FormsAuthentication不保留UserData字段

Dom*_*icz 2 asp.net cookies formsauthentication

FormsAuthenticationTicket从零开始创建了一个,但发现在以后检索它时,UserData它不会回来.这是使用的代码:

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                        1,
                        user.UserId,
                        DateTime.Now,
                        DateTime.MaxValue,
                        false,
                        user.UserType);

HttpCookie cookie = new HttpCookie(
     FormsAuthentication.FormsCookieName, 
     FormsAuthentication.Encrypt(ticket));

Response.Cookies.Add(cookie);
Run Code Online (Sandbox Code Playgroud)

但是,当读到下一个时Request,我发现该UserData字段现在是空的:

string encryptedCookie = Request.Cookies[ FormsAuthentication.FormsCookieName ].Value;
FormsAuthenticationticket ticket = FormsAuthentication.Decrypt(encryptedCookie);
Assert.IsTrue( ticket.UserData.Length == 0 ); //TRUE!
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Dom*_*icz 9

我想我发现了这个问题.如果你自己编写了cookie名称,那就好了!所以转变自:

HttpCookie cookie = new HttpCookie(
     FormsAuthentication.FormsCookieName, 
     FormsAuthentication.Encrypt(ticket));
Run Code Online (Sandbox Code Playgroud)

HttpCookie cookie = new HttpCookie(
     "SiteCookie", 
     FormsAuthentication.Encrypt(ticket));
Run Code Online (Sandbox Code Playgroud)

然后根据问题检索它:

string encryptedCookie = Request.Cookies[ "SiteCookie" ].Value;
FormsAuthenticationticket ticket = FormsAuthentication.Decrypt(encryptedCookie);
Assert.IsFalse( ticket.UserData.Length == 0 ); //Hooray! It works
Run Code Online (Sandbox Code Playgroud)

它可能的.NET做了一些棘手的东西,所以把它放在一个新的工作正常.

更新:

此外,需要刷新票证,否则票证将在用户使用网站时到期:

FormsAuthentication.RenewTicketIfOld(ticket); // Do before saving cookie
Run Code Online (Sandbox Code Playgroud)