Login and Logout Sample

Raj.Trivedi
Posted by Raj.Trivedi under ASP.NET category on | Points: 40 | Views : 1896
Here I have taken 2 Pages

1.Login.aspx
2.Welcome.aspx

If the user inputs the username and password i am storing the username in the session and redirecting them to Welcome.aspx
and if Session is null then it will redirect to login page.

On the Welcome page there is a Logout Button.On clicking it the session will expire and the user will be redirected to login page.

When the user open the tab and tries to call directly the welcome.aspx he will be redirected to login check this code.

Login.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>

<form id="form1" runat="server">
<div>
Username :- <asp:TextBox ID="xtxtUserName" runat="server"></asp:TextBox><br />
Password :- <asp:TextBox ID="xtxtPassword" TextMode="Password" runat="server"></asp:TextBox><br />
<asp:Button ID="xLogin" runat="server" Text="Button" onclick="Login_Click" />

</div>

</form>
</body>
</html>

Code behind.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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

}
protected void Login_Click(object sender, EventArgs e)
{
string Username = xtxtUserName.Text;
string password = xtxtPassword.Text;
Session["Username"] = xtxtUserName.Text;
Response.Redirect("~/Welcome.aspx");
}
}

Welcome.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Welcome.aspx.cs" Inherits="Welcome" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:Label ID="lblUsername" runat="server" Text=""></asp:Label>
&nbsp;&nbsp; Welcome&nbsp;
<asp:LinkButton ID="xlnklogout" runat="server" onclick="xlnklogout_Click">Log Out</asp:LinkButton>
</div>
</form>
</body>
</html>

Code behind of welcome page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Welcome : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["Username"] == null)
{
Response.Redirect("~/Login.aspx");
}
else
{
lblUsername.Text = Session["Username"].ToString();
}
}
}
protected void xlnklogout_Click(object sender, EventArgs e)
{
Session.Clear();
Session.Abandon();
Response.Redirect("~/Login.aspx");
}
}

Comments or Responses

Login to post response