1

我一直在爭取這一段時間。在VS 2012中,我使用「Internet應用程序」項目模板創建了一個新的MVC4應用程序(爲了簡單起見,我還在使用ExtendedMembershipProvider的常規應用程序中看到了這個問題)。FormsAuthentication不會將UserData保存在默認的MVC4 Web應用程序模板中

在登錄我想把一些的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的值,並將其與登錄請求後瀏覽器中顯示的值進行比較來證明這一點。他們是不同的!有些東西正在重新創建cookie並對其進行加密,而不存在UserData。名稱值存在於cookie中 - 任何想法在哪裏或將要做什麼? MS使用新的WebMatrix方法在表單身份驗證中破壞了UserData?

+0

嗨!它終於爲你工作了嗎? – akjha627

回答

3

您正在設置Cookie的請求,您需要在Response對象上設置cookie。

+0

哇 - 我不敢相信我沒有看到。愚蠢的錯誤。 –

相關問題