如何在asp.net网站上获取cookie值

时间:2011-12-13 13:35:36

标签: c# asp.net cookies forms-authentication

我正在创建一个cookie并在成功登录后存储用户名的值。如何在网站打开时访问cookie。如果cookie存在,我想填写cookie值的用户名文本框。以及如何解密该值以获取用户名。我通过从数据库获取用户详细信息来进行服务器端验证。我正在使用vs 2010与c#

FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
    DateTime.Now.AddYears(1), chk_Rememberme.Checked, "User Email");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);

if (chk_Rememberme.Checked)
{
    ck.Expires = tkt.Expiration;
    ck.Path = FormsAuthentication.FormsCookiePath;
    Response.Cookies.Add(ck);
}
创建

cookie,名称为.YAFNET_Authentication,内容已加密

Webconfig:

  <forms name=".YAFNET_Authentication" loginUrl="Home.aspx"
  protection="All" timeout="15000" cookieless="UseCookies"/>

4 个答案:

答案 0 :(得分:76)

您可以使用Request.Cookies集合来阅读Cookie。

if(Request.Cookies["key"]!=null)
{
   var value=Request.Cookies["key"].Value;
}

答案 1 :(得分:18)

FormsAuthentication.Decrypt获取cookie的实际值,而不是它的名称。你可以获得像

这样的cookie值
HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value;

并解密。

答案 2 :(得分:8)

将此功能添加到您的global.asax

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    string cookieName = FormsAuthentication.FormsCookieName;
    HttpCookie authCookie = Context.Request.Cookies[cookieName];

    if (authCookie == null)
    {
        return;
    }
    FormsAuthenticationTicket authTicket = null;
    try
    {
        authTicket = FormsAuthentication.Decrypt(authCookie.Value);
    }
    catch
    {
        return;
    }
    if (authTicket == null)
    {
        return;
    }
    string[] roles = authTicket.UserData.Split(new char[] { '|' });
    FormsIdentity id = new FormsIdentity(authTicket);
    GenericPrincipal principal = new GenericPrincipal(id, roles);

    Context.User = principal;
}

然后您可以使用HttpContext.Current.User.Identity.Name来获取用户名。希望它有所帮助

答案 3 :(得分:0)

HttpCookie cook = new HttpCookie("testcook");
cook = Request.Cookies["CookName"];
if (cook != null)
{
    lbl_cookie_value.Text = cook.Value;
}
else
{
    lbl_cookie_value.Text = "Empty value";
}

参考Click here