0

我有两个代码块,它们应该做同样的工作,即复制整个代码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);
}
4

1 回答 1

2

如果您查看示例 2 中使用的 GetAuthCookie()方法的 MSDN,您会看到它说:

为给定的用户名创建一个身份验证 cookie。

这意味着当您在示例 2 中进行此调用时,您实际上得到的是刚刚创建的全新身份验证 cookie,而不是您已经设置的身份验证 cookie。这就是该UserData属性为空/null 的原因。

于 2015-01-21T16:06:47.810 回答