Hello Shanky11,
Check this.
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>
<asp:TextBox ID="xtxtUserName" runat="server"></asp:TextBox><br />
<asp:TextBox ID="xtxtPassword" 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>
Welcome
<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");
}
}
Regard's
Raj.Trivedi
"Sharing is Caring"
Please mark as answer if your Query is resolved
Shanky11, if this helps please login to Mark As Answer. | Alert Moderator