Wednesday 12 February 2014

How to maintain User Login information in Cookies using C#.net

In this article I will explain how to maintain User Login information in Cookies using C#.net.

I have a login screen. In that screen two textboxes (txtUserName, txtPassword) and one button (btnSubmit).

If the end user entered the username and password and clicked the Submit button, we are maintained the user information in cookies. Check the below code.

protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        { 
            objclLogin.UserName = txtUserName.Text;
            objclLogin.Password = txtPassword.Text;
            // Checking if the user is valid or not
            dsLogin = objclLogin.ValidateUser();
            if (dsLogin.Tables[0].Rows.Count > 0)
            {
                if (dsLogin.Tables[0].Rows[0][0].ToString() == "1")
                {
                    string UserDetails;
                    dsUserDetails = objclLogin.GetUserDetails();                    
                    UserDetails = dsUserDetails.Tables[0].Rows[0][0].ToString();                   
                    FormsAuthenticationTicket Ticket;
                    string cookiestr;
                    HttpCookie ck;
                    Ticket = new FormsAuthenticationTicket(1, txtUserName.Text, DateTime.Now, DateTime.Now.AddMinutes(30), true, UserDetails);
                    cookiestr = FormsAuthentication.Encrypt(Ticket);
                    ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
                    ck.Path = FormsAuthentication.FormsCookiePath;
                    Response.Cookies.Add(ck);
                    Response.Redirect("Home.aspx");

                }
            }
        }
        catch (Exception Ex) { } 
    }


No comments:

Post a Comment