Use of Session in ASP.NET

Use of Session 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 the 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, that without login the home page will not 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");

    }

}