How to get the cookie value in asp.net website

后端 未结 4 1683
渐次进展
渐次进展 2020-12-23 13:56

I am creating a cookie and storing the value of username after succesfull login. How can I access the cookie when the website is opened. If the cookie exist I want to fill t

相关标签:
4条回答
  • 2020-12-23 14:27

    FormsAuthentication.Decrypt takes the actual value of the cookie, not the name of it. You can get the cookie value like

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

    and decrypt that.

    0 讨论(0)
  • 2020-12-23 14:28

    You may use Request.Cookies collection to read the cookies.

    if(Request.Cookies["key"]!=null)
    {
       var value=Request.Cookies["key"].Value;
    }
    
    0 讨论(0)
  • 2020-12-23 14:32

    add this function to your 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;
    }
    

    then you can use HttpContext.Current.User.Identity.Name to get username. hope it helps

    0 讨论(0)
  • 2020-12-23 14:39
    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";
    }
    

    Reference Click here

    0 讨论(0)
提交回复
热议问题