读取FormsAuthenticationTicket时的结果不同

时间:2015-01-21 12:31:18

标签: asp.net-mvc forms-authentication formsauthentication formsauthenticationticket

我有两个代码块应该执行相同的工作,即复制整个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);
}

1 个答案:

答案 0 :(得分:2)

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

  

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

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