在你的代碼寫的cookie,你不能傳遞一個空的用戶數據參數與加密的Cookie。 IsPersistent爲false是好的。
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket
(1, user.UserEmail, DateTime.Now,
DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
false, null);
做這樣的事情如下: 在我的例子,你可以用一個空字符串替換userData.ToString()。只是不要將它傳遞給null!這應該能解決你的問題。
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事件 您的代碼將在這裏有所不同的是餅乾,我寫了一個自定義表單認證和正在使用用戶ID,而不是電子郵件中你的情況。
如果您在編寫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.");
}
}
感謝您的建議。我實際上是重定向,在此之後,正常的cookie可用,票不是。 – acullen72