Click here to Skip to main content
11,718,289 members (81,564 online)
Click here to Skip to main content

User Session in ASP.NET

, 22 Aug 2015 CPOL 2.2K 1
Rate this:
Please Sign up or sign in to vote.
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:

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:

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)
    {
        Response.Redirect("Login.aspx");
    }
}

License

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

Share

About the Author

Deepak Kr Choudhary
Instructor / Trainer
India India
No Biography provided

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150901.1 | Last Updated 22 Aug 2015
Article Copyright 2015 by Deepak Kr Choudhary
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid