Click here to Skip to main content
15,305,754 members
Articles / Web Development / ASP.NET
Posted 22 Aug 2015


1 bookmarked

User Session in ASP.NET

Rate me:
Please Sign up or sign in to vote.
1.00/5 (4 votes)
22 Aug 2015CPOL1 min read
This article is about the session use in ASP.NET.


Session State information is available to all the pages opened by a user, during a single visit.

Step 1

Create a Master Page First, like the following image:

Step 2

Create a Login page using the Master page.

Write a code to create the Session:

protected void LoginButton_Click(object sender, EventArgs e)
    if (LoginUser.UserName == "deepak" && LoginUser.Password == "123")
        //here I am creating a session and store login name to session user
        Session["user"] = LoginUser.UserName;

Now, what I want to do is, when the user clicks on the login button, the condition should be executed after the condition returns true, login name is stored in session, and the page gets redirected to the home page and on top of the home page, the Login name will display like the following:

welcome Deepak Logout

And Linkbutton text will change the Login to Logout such as the following image:

To achieve this, write the following code in the master page page_load event:

protected void Page_Load(object sender, EventArgs e)
    if (Session["user"] != null)
        Label1.Text = Session["user"].ToString();
        LinkButton1.Text = "Logout";

When the Welcome message displays with the user name, then the user should be able to click on Logout, and the session will expire, and the page shall redirect to the login page.

To achieve this, write the following code in the master page Link_click event: protected void LinkButton1_Click(object sender, EventArgs e) { Session.Abandon(); Response.Redirect("Login.aspx"); }

Note: If you want to restrict the user, without login, the home page will not be accessible.

For this, you need to write the following code in the home page page_load event.

protected void Page_Load(object sender, EventArgs e)
    if (Session["user"] == null)


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Deepak Kr Choudhary
Instructor / Trainer
India India
No Biography provided

Comments and Discussions

-- There are no messages in this forum --