Save Username and Password in Cookies using C# in ASP.Net

Last Reply 15 days ago By dharmendr

Posted one month ago

How i save login username and password usgin Cookie in ASP.NET C#

Any example on how to save username accross pages?

this is my signup, but i want to use cookies to store user username and password, the resaon is because the session expires when the user closes the browser, which throws error on page. So i dont want the user to keep login in all the time thats why i want to store the user username and password the first time the user sign up so that when the user logins in ones the website will keep the user login all the time.

                               string constr = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
                               using (SqlConnection con = new SqlConnection(constr))
                               {
                                   using (SqlCommand cmd = new SqlCommand("Insert_Users"))
                                   {
                                       using (SqlDataAdapter sda = new SqlDataAdapter())
                                       {
                                           //Get Filename from fileupload control
                                           // string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
                                           //Save images into Images folder
                                           //   FileUpload1.SaveAs(Server.MapPath("UserImages/" + filename));
                                           cmd.CommandType = CommandType.StoredProcedure;
                                           //  cmd1.Parameters.AddWithValue("@UserImageName", filename);
                                           // cmd1.Parameters.AddWithValue("@UserImagePath", "UserImages/" + filename);
                                           cmd.Parameters.AddWithValue("@Name", txtName.Text.Trim());
                                           cmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim());
                                           cmd.Parameters.AddWithValue("@UserName", UsrNm);
 
                                           cmd.Parameters.AddWithValue("@Password", Encrypt(txtPassword.Text.Trim()));
 
                                           cmd.Parameters.AddWithValue("@BirthDay", txtBirthDay.Text.Trim());
 
                                           cmd.Parameters.AddWithValue("@Country", ddlCountry.Text.Trim());
                                           cmd.Parameters.AddWithValue("@ImageName", imgname);
                                           cmd.Connection = con;
                                           con.Open();
                                           UserID = Convert.ToInt32(cmd.ExecuteScalar());
                                           con.Close();
 
 
                                       }
                                   }
                                   string message = string.Empty;
                                   switch (UserID)
                                   {
                                       case -1:
                                           message = "Username already exists.\\Please choose a different username.";
                                           break;
                                       case -2:
                                           message = "Supplied email address has already been used.";
                                           break;
 
                                       
                                       default:
                                           message = "Registration successful, you may now login.";
                                          // SendActivationEmail(UserID);
                                           break;
                                   }
                                   ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + message + "');", true);
                               }
                           }
                       }

 

Posted 15 days ago

Hi micah,

Check this example. Now please take its reference and correct your code.

HTML

<table border="0" cellpadding="0" cellspacing="0">
    <tr>
        <td>
            User Name
        </td>
        <td>
            <asp:TextBox ID="txtName" runat="server" />
        </td>
    </tr>
    <tr>
        <td>
            Password
        </td>
        <td>
            <asp:TextBox ID="txtPassword" runat="server" />
        </td>
    </tr>
    <tr>
        <td>
            <asp:Button Text="Login" runat="server" OnClick="LogIn" />
        </td>
    </tr>
</table>

C#

protected void LogIn(object sender, EventArgs e)
{
    bool valid = false;
    //Validate Name and Password with database.
    if (txtName.Text.Trim().ToLower() == "sa" && txtPassword.Text.Trim().ToLower() == "sa")
    {
        valid = true;
    }
    if (valid)
    {
        //Create a Cookie with a suitable Key.
        HttpCookie loginCookie = new HttpCookie("Login");
        //Set the Cookie value.
        loginCookie.Values["Name"] = txtName.Text;
        loginCookie.Values["Password"] = txtPassword.Text;
        loginCookie.Path = Request.ApplicationPath;
        //Set the Expiry date.
        loginCookie.Expires = DateTime.Now.AddDays(1);
        //Add the Cookie to Browser.
        Response.Cookies.Add(loginCookie);
        Response.Redirect("Home.aspx");
    }
    else
    {
        Response.Redirect("Login.aspx");
    }
}

You need to write the below code in your MasterPage. If you don't have master page then you need to write the code in each page for checking the validation with database record.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        HttpCookie loginCookie = Request.Cookies["Login"];
        if (loginCookie != null)
        {
            string name = loginCookie.Values["Name"];
            string password = loginCookie.Values["Password"];
            // User validation based on cookies if required for valid user as might be user can change his password in any cases
            // so call your databse user login validation method
            if (name.ToLower() == "sa" && password.ToLower() == "sa") // user validation code 
            {
                Response.Redirect("Home.aspx");
            }
            else
            {
                Response.Redirect("Login.aspx");
            }
        }
    }
}

Note: Here i have hardcoded the value. So you need to change as per your requirement.

I agree, here is the link: https://www.e-iceblue.com/Introduce/spire-office-for-net-free.html