FormsAuthentication不是$ P $在.NET 3.5 pserving该领域的UserData回发后 [英] FormsAuthentication isn't preserving the UserData field after Postback in .NET 3.5

查看:153
本文介绍了FormsAuthentication不是$ P $在.NET 3.5 pserving该领域的UserData回发后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个的FormsAuthenticationTicket 从头开始,却发现在稍后的时间检索时,在的UserData 不回来了。下面是使用code:

I've created a FormsAuthenticationTicket from scratch, but found that when retrieving it at a later time, the UserData isn't coming back. Here is the code used:

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

不过,看完就下请求这回来的时候,我发现的UserData 字段现在是空的:

However, when reading this back on the next Request, I found that the UserData field is now empty:

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

任何想法?

推荐答案

我想我找到了问题。如果你弥补自己的cookie的名称似乎是罚款!因此,从改变:

I think I found the problem. If you make up your own cookie name it seems to be fine! So change from:

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

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

,然后检索它作为每一个问题:

And then retrieve it as per the question:

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

其可能.NET做一些棘手的东西呢,所以,将其置于一个新的正常工作。

Its possible .NET does some tricky stuff with it, so by putting it in a new one works fine.

更新:

另外,需要刷新,因为否则车票将在用户使用该网站到期票:

Also, the ticket needs to be refreshed, as otherwise the ticket will expire while the user is using the website:

FormsAuthentication.RenewTicketIfOld(ticket); // Do before saving cookie

这篇关于FormsAuthentication不是$ P $在.NET 3.5 pserving该领域的UserData回发后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆