1

我已经和这个斗争了一段时间。在 VS 2012 中,我使用“Internet 应用程序”项目模板创建了一个新的 MVC4 应用程序(为简单起见,我还在使用 ExtendedMembershipProvider 的常规应用程序中看到了问题)。

在登录时,我想将一些 UserData 放入表单身份验证 cookie,因此我使用以下代码:

public ActionResult Login(LoginModel model, string returnUrl)
{
    Request.Cookies.Remove(FormsAuthentication.FormsCookieName);
    if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
    {
        HttpCookie authCookie = FormsAuthentication.GetAuthCookie(model.UserName, true);
        string userData = "This is some test data.";
        FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
        FormsAuthenticationTicket newAuthTicket = new FormsAuthenticationTicket(authTicket.Version, authTicket.Name, authTicket.IssueDate, authTicket.Expiration, authTicket.IsPersistent, userData);
        string newAuthTicketEncrypted = FormsAuthentication.Encrypt(newAuthTicket);
        authCookie.Value = newAuthTicketEncrypted;

        Request.Cookies.Set(authCookie);
        // Response.Write("Encrypted cookie value: " + authCookie.Value);  // value here differs than what browser sees
        // Response.Write("UserData: " + FormsAuthentication.Decrypt(authCookie.Value).UserData + "<br/>"); // userdata is present here.
        // return, shortened for brevity

    }

}

很基本。但是,当我解密它时,它不存在于 cookie 中。问题似乎是在管道中的其他地方创建了一个新的表单身份验证 cookie。我可以通过打印出加密 cookie 的值并将其与登录请求后出现在浏览器中的值进行比较来证明这一点。它们是不同的!在没有 UserData 的情况下,某些东西正在重新创建 cookie 并对其进行加密。名称值存在于 cookie 中——知道在哪里或做什么吗?MS 是否使用新的 WebMatrix 方法在表单身份验证中破坏了 UserData?

4

1 回答 1

3

您正在根据需要在 Response 对象上设置 cookie 的请求设置 cookie。

于 2013-10-29T18:56:26.350 回答