How to get the cookie value in asp.net website

后端 未结 4 1682
渐次进展
渐次进展 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: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

提交回复
热议问题