我创建了一个Web Forms Application
项目,仅用于测试此案例。我正在使用.NET4
框架的默认网页模板,没有任何修改,Default.aspx
页面上有3个按钮和1个标签。
按钮: btnLogin
,btnSetCookie
,btnGetCookie
标签: lblCookieInfo
流量:
Set Cookie
按钮Get Cookie
按钮现在,当我点击第三个按钮来检索cookie时,到达Decrypt
方法(Invalid value for 'encryptedTicket' parameter
)时总是会抛出错误。
当我尝试将cookie检索到httpCookie
时,该空白没有任何值。
我做错了什么?
protected void btnLogin_Click(object sender, EventArgs e)
{
FormsAuthentication.SetAuthCookie("myUserName", createPersistentCookie: true);
Response.Redirect("~/");
}
protected void btnSetCookie_Click(object sender, EventArgs e)
{
var ticket = new FormsAuthenticationTicket(1,
"myUserName",
DateTime.Now,
DateTime.Now.AddMinutes(10),
true,
"data value of cookie",
FormsAuthentication.FormsCookiePath);
string encTicket = FormsAuthentication.Encrypt(ticket);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
{
Expires = ticket.Expiration,
HttpOnly = true
};
btnGetCookie.Enabled = true;
Response.Cookies.Add(authCookie);
}
protected void btnGetCookie_Click(object sender, EventArgs e)
{
var httpCookie = Response.Cookies[FormsAuthentication.FormsCookieName];
lblCookieInfo.Visible = true;
if (httpCookie == null)
{
lblCookieInfo.Text = "Cookie is Null";
return;
}
//Here throws error!
var decryptedCookie = FormsAuthentication.Decrypt(httpCookie.Value);
if (decryptedCookie == null)
{
lblCookieInfo.Text = "Cookie can't be decrypted.";
return;
}
lblCookieInfo.Text = string.Format("Name: {0}, Is Expired: {1}, Is Persistent: {2}, Expiration: {3}, Path: {4}, User data: {5}",
decryptedCookie.Name, decryptedCookie.Expired,
decryptedCookie.IsPersistent, decryptedCookie.Expiration,
decryptedCookie.CookiePath, decryptedCookie.UserData);
}
答案 0 :(得分:1)
我真的不记得我是如何解决它但我创建了以下课程。我认为问题是FormsAuthenticationTicket(...)
函数中的一个参数。
public static class EncryptedCookie
{
public static HttpCookie SetEncryptedCookie(string name, DateTime expiration, bool httpOnly, string userData, string cookiePath)
{
var ticket = new FormsAuthenticationTicket(1, name, DateTime.Now, expiration, false, userData, cookiePath);
string encTicket = FormsAuthentication.Encrypt(ticket);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
{
Expires = ticket.Expiration,
HttpOnly = httpOnly
};
return authCookie;
}
public static FormsAuthenticationTicket GetEncryptedCookie(HttpCookie cookie)
{
if (cookie == null || string.IsNullOrEmpty(cookie.Value)) return null;
FormsAuthenticationTicket decryptedCookie;
try
{
decryptedCookie = FormsAuthentication.Decrypt(cookie.Value);
if (decryptedCookie == null || string.IsNullOrEmpty(decryptedCookie.Name) || decryptedCookie.Expired) return null;
}
catch
{
return null;
}
return decryptedCookie;
}
public static void RemoveCookie(string cookieName)
{
HttpContext.Current.Request.Cookies.Remove(cookieName);
}
}