我有两个代码块,它们应该做同样的工作,即复制整个代码FormsAuthenticationTicket
并更改其中存储在UserData
.
第一个代码正确读取所有内容,包括UserData
. 第二个不包括UserData
。它只是返回一个空字符串。我意识到,当一个异常被抛出是因为如果一个空对象。
任何的想法?
第一个代码:
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = HttpContext.Request.Cookies[cookieName];
if (authCookie != null)
{
FormsAuthenticationTicket oldTicket = FormsAuthentication.Decrypt(authCookie.Value);
UserData userDataObj = JsonConvert.DeserializeObject<UserData>(oldTicket.UserData);
userDataObj.PassChangeRequired = user.PasswordChangeRequired;
string userdata = JsonConvert.SerializeObject(userDataObj);
FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(
oldTicket.Version,
oldTicket.Name,
oldTicket.IssueDate,
oldTicket.Expiration,
oldTicket.IsPersistent,
userdata,
oldTicket.CookiePath);
authCookie.Value = FormsAuthentication.Encrypt(newTicket);
Response.Cookies.Set(authCookie);
}
第二个代码:
HttpCookie authCookie = FormsAuthentication.GetAuthCookie(user.UserName, false);
if (authCookie != null)
{
FormsAuthenticationTicket oldTicket = FormsAuthentication.Decrypt(authCookie.Value);
UserData userDataObj = JsonConvert.DeserializeObject<UserData>(oldTicket.UserData);
userDataObj.PassChangeRequired = user.PasswordChangeRequired;
string userdata = JsonConvert.SerializeObject(userDataObj);
FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(
oldTicket.Version,
oldTicket.Name,
oldTicket.IssueDate,
oldTicket.Expiration,
oldTicket.IsPersistent,
userdata,
oldTicket.CookiePath);
authCookie.Value = FormsAuthentication.Encrypt(newTicket);
Response.Cookies.Set(authCookie);
}