If you are building simple application which require less security, here is a simpler way to do it.
It gives you a very basic idea.
You can build a class for storing user login credentials in session sate something like this:
public class LoginUser
{
public static bool IsLogin
{
get
{
if (HttpContext.Current == null ||
HttpContext.Current.Session == null ||
HttpContext.Current.Session["IsLogin"] == null)
return false;
return (bool)HttpContext.Current.Session["IsLogin"];
}
set
{
HttpContext.Current.Session["IsLogin"] = value;
}
}
public static string Username
{
get
{
return HttpContext.Current.Session["Username"] + "";
}
set
{
HttpContext.Current.Session["Username"] = value;
}
}
}
a simple example of code behind of login page:
protected void Page_Load(object sender, EventArgs e)
{
if (LoginUser.IsLogin)
Response.Redirect("~/Default.aspx", true);
}
protected void btLogin_Click(object sender, EventArgs e)
{
LoginUser.IsLogin = true;
LoginUser.Username = txtUsername.Text;
Response.Redirect("~/Default.aspx", true);
}
And the code behind of Default.aspx page:
protected override void OnInit(EventArgs e)
{
if (!LoginUser.IsLogin)
{
Response.Redirect("~/Login.aspx", true);
return;
}
base.OnInit(e);
}
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("User logged In: " + LoginUser.Username);
}
And you can clear the session state values during Logout:
public partial class Logout : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Session.RemoveAll();
Session.Clear();
Session.Abandon();
Response.Clear();
Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddSeconds(-30);
Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
}
}