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

Posted

技术标签:

【中文标题】如何在asp.net网站中获取cookie值【英文标题】:How to get the cookie value in asp.net website 【发布时间】:2012-01-19 09:07:46 【问题描述】:

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

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);

创建名称为 .YAFNET_Authentication 的 cookie 并加密内容

网络配置:

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

【问题讨论】:

【参考方案1】:

您可以使用Request.Cookies 集合来读取cookies。

if(Request.Cookies["key"]!=null)

   var value=Request.Cookies["key"].Value;

【讨论】:

【参考方案2】:

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

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

然后解密。

【讨论】:

【参考方案3】:

将此函数添加到您的 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 来获取用户名。希望对你有帮助

【讨论】:

【参考方案4】:
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

【讨论】:

以上是关于如何在asp.net网站中获取cookie值的主要内容,如果未能解决你的问题,请参考以下文章

如何在 ASP.NET MVC 网站中为 cookie 设置“安全”标志?

在 cookie 中存储 JWT 令牌后,如何在 ASP.NET Core 3.1 中破坏该 cookie 并获取信息

如何从php中的asp.net发送的cookie中检索特定值

如何在 ASP.NET Core 中获取我网站的 baseurl?

如何在 ASP.NET 中获取登录用户信息

如何在 ASP.NET 中将 SameSite cookie 属性减少回无?