【发布时间】:2015-03-06 19:00:05
【问题描述】:
我创建了一个Web Forms Application 项目只是为了测试这个案例。我使用.NET4框架的默认Web模板,没有任何修改,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);
}
【问题讨论】:
-
你能确定为什么这会引发异常吗?我现在有类似的问题,我无法隔离。我注意到这段代码没有检查此处提到的空 cookie 值:stackoverflow.com/questions/18895746/… 这可能会有所帮助,但我仍然很好奇为什么它会是空的?
-
@mklinker 我现在不记得了,但我记得问题非常简单。很可能就是你所说的。
-
@mklinker 请看看下面我的回答,它可能对你有帮助......
-
感谢您的跟进,我看到了额外的 cookie 值检查以及 try...catch - 我会做类似的事情;仍然希望我真的了解如何以及为什么
标签: asp.net cookies encryption webforms form-authentication