Custom Login control with session and cookies in ASP.NET

Introduction

Cookies is a Text file , which is sent by web server and saved on client machine. As Well as Session saved on server machine. Here we take a simple example, first we will create a sessionId, After that saved it into cookies.

Designing pattern 

Step-1 : Create Database table with some column , these are

sno  int  primary_key column with automatic increment
username  nvarchar(50)
password nvarchar(50)
userID  nvarchar(max)

Step-2 : Fill this table with some data.
Step-3 : Design Login Control with proper validation, look like
Design Login Control with proper validation

Code View

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;


public partial class logincontrol : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    

        if (Request.Cookies["mycookie"]!= null)
        {
            Response.Redirect("~/welcome.aspx");

        }

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        bool flag = true;

        SqlConnection con = new SqlConnection();
                con.ConnectionString =ConfigurationManager .ConnectionStrings ["ConnectionString"].ToString ();
        con.Open ();
        SqlCommand cmd=new SqlCommand ();
        cmd.CommandText ="select * from usertable";
        cmd.Connection =con;
        SqlDataReader rd=cmd.ExecuteReader ();
        while (rd.Read ())
{
        if (TextBox1 .Text ==rd["username"].ToString () && TextBox2 .Text ==rd["password"].ToString ())
{
        Session["userID"] = rd["userID"].ToString ();
        flag = false;
        break;

}
}
        if (flag == false)
        {
            if (CheckBox1.Checked)
            {
                HttpCookie mycookie = new HttpCookie("mycookie");

                Response.Cookies["mycookie"]["userID"] = Session["userID"].ToString();
                Response.Redirect("~/welcome.aspx");
               

            }
            else
            {
                Response.Redirect("~/welcome.aspx");

            }


        }
        else
        {
            Label1.Text = "username and password wrong";
            Label1.ForeColor = System.Drawing.Color.Red;
        }
        
    }
}

Code generate the following output

Custom Login control with session and cookies in ASP.NET

Custom Login control with session and cookies in ASP.NET

First check cookies on page_load method, if exists in browser, directly you can navigate to welcome page. If doesn't then you will interface with login page. Create session and save into cookies after select checkbox.

Comments

Popular posts from this blog

difference between structure and union in C Language

Difference between Linear search and Binary Search in c language

Difference between static and dynamic websites