Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

User Session in ASP.NET

1.00/5 (4 votes)
22 Aug 2015CPOL1 min read 10.9K  
This article is about the session use in ASP.NET.

Session

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:

C#
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;
        Response.Redirect("Default.aspx");
    }
}

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:

C#
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.

C#
protected void Page_Load(object sender, EventArgs e)
{
    if (Session["user"] == null)
    {
        Response.Redirect("Login.aspx");
    }
}

License

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