在编写 cookie 的代码中,您不能将 null 传递给带有加密 cookie 的 userData 参数。IsPersistent 为 false 很好。
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket
(1, user.UserEmail, DateTime.Now,
DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
false, null);
执行以下操作:在我的示例中,您可以将 userData.ToString() 替换为空字符串。只是不要给它一个空值!那应该可以解决您的问题。
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // version
userId.UserEmail, // a unique value that identifies the user
DateTime.Now, // created
DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes), // expires
false, // persistent?
userData.ToString(), // user specific data (optional) //NOTE: DO NOT pass NULL as encrypted string value will become NULL (argh)
FormsAuthentication.FormsCookiePath // the path for the cookie
);
然后在您的 global.asax.cs 中,您将在 FormsAuthentication_OnAuthenticate 事件中检查该 cookie 您的代码将在此处有所不同,因为我已经编写了自定义表单身份验证,并且在您的情况下使用的是 userId 而不是电子邮件。
请注意以下逻辑,如果您在编写 auth cookie 时为 UserData 参数传递 null,则会失败。
if (authCookie == null || authCookie.Value == "")
{
return;
}
以下是 globalasax.cs 文件中的完整事件:
protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
{
//STEP #1 of Authentication/Authorization flow
//Reference: http://msdn.microsoft.com/en-us/library/ff649337.aspx
//==================================================================
if (FormsAuthentication.CookiesSupported == true)
{
//Look for an existing authorization cookie when challenged via [Authorize]
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null || authCookie.Value == "")
{
return;
}
FormsAuthenticationTicket authTicket = null;
try
{
//Reading from the ticket
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
//Check the Cookiename (which in this case is UserId). If it is null, then we have an issue
if (authTicket.Name == null)
{
FormsAuthentication.SignOut();
authCookie.Value = null;
}
}
catch (Exception ex)
{
//Unable to decrypt the auth ticket
return;
}
//get userId from ticket
string userId = authTicket.Name;
Context.User = new GenericPrincipal(
new System.Security.Principal.GenericIdentity(userId, "MyCustomAuthTypeName"), authTicket.UserData.Split(','));
//We are officially 'authenticated' at this point but not neccessarily 'authorized'
}
else
{
throw new HttpException("Cookieless Forms Authentication is not supported for this application.");
}
}