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 aresno 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
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;
}
}
}