How to create and maintain Sessions in ASP.NET using C#
ASP.net Sessions are special type of objects which allow use to store and retrieve data for a user, as the user navigates throughout the ASP.NET Web Application. Data stored in a Session object contains the information for a single user and is available to all the pages throughout the application.
For every user, a new session object is created and is destroyed when it gets expired. Usually, in ASP.NET, the time period for a session expiry is around 20 minutes by default, which can be changed through Web.config file in Visual Studio, which will be discussed later in this article.
The best use for Sessions is to maintain the login session, which may contain the username, and its roles, which can be helpful to control the user access to certain parts of the application. Another use may to be transfer data from one page to another which can be obtained easily through Session Object.
A Session has two important parts:
Key uniquely identifies the session object and the value is the data assigned and stored in that session object.
Following is the working example of Session in c#
Session["FirstName"] = txtFirstName.Text; Session["LastName"] = txtLastName.Text;
Another example for maintaining the username might be as follows:
Session["username"] = txtUserName.Text; Session["role"] = "admin";
In the above mentioned example, a session is being created whose key is "username" and the value assigned to it is the text in txtUserName. Same is the case with "Role" session object. Now the username and its role can be retrieved and accessed from anywhere within the web application.
if(Session["username"] == null) Response.Redirect("Login.aspx"); if(Session["role"] == "admin") //code which is accessible to the admin
If you want to destroy a specific session, use:
Or this can be used to abandon the Sessions
Change timeout of Session through Web.config
The timeout of Session can be edited through Web.config file in Visual studio. Following is the code for it.
<configuration> <system.web> <sessionState timeout="10"></sessionState> </system.web> </configuration>
The timeout is mentioned in minutes, so the above code will change the timeout to 10 minutes.