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

本文关键字:获取 cookie 网站 net asp | 更新日期: 2023-09-27 18:17:56

我正在创建一个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和内容已加密

网络配置:

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

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

您可以使用 Request.Cookie 集合来读取 Cookie:

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

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

HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value;

并解密。

将此函数添加到全局.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 来获取用户名。 希望有帮助

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";
}

参考资料 点击这里