Introduction
This article explains Session Management in the ASP.NET Web API and shows how to use it. Sessions perform the work like a cookie that stores and retrieves information.
What is Session State
Session state provides a way to store and fetch information of the user that can be stored in one page and fetched on another page. When a user logs into a website and the user name is displayed on all the pages of the website, this is done by the session. We store the user name in the session variable and access that variable for all the pages.
Ex. Session["Name"] = Textbox.Text;
In this example we store the "TextBox" value in the Session variable "Name". Any text that can be written in the TextBox is stored in the Session variable "Name".
Session Variable
Session variables are stored in the object of the "SessionStateItemCollection" class. This class manages the values of the session state variable values. In the preceding example we created a session variable "Name" and that value is fetched from the "TextBox". This variable is indexed by the variable name.
Now let's see an example of the Session Management in the Web API.
Step 1
Create the Web API application
Create the Web API application using the following procedure:
From the start window select "New Project".
In the Template Window select "Installed" -> "Visual C#" -> "Web".
Select "ASP.NET MVC 4 Web Application" and click on "OK".
Step 2
Create a model class using the following procedure:
Add the following code:
Step 3
Now open the "HomeCOntroller" file using the following procedure:
Step 4
Create a "UserSessionSection.cshtml" file using the following procedure:
In the "HomeController" file.
Right-click n the "UsersessionSection" Action then select "Add View".
Click on the "Ok" button.
Add the following code,
Step 5
Now open the "index.cshtml" file using the following procedure:
In the "Solution Explorer".
Select "Views" -> "Home" -> "index.cshtml".
Step 6
Add the line of code in the Web.config file. It exists in the.
In this code timeout="1"specifes that after 1 minute the session will be expire. If we not specify the time then by default the time for expiring the session is 20 minutes.
Step 7
Execute the application; press "F5".Enter the User Name and User Password and click on the submit button.
The output looks like this,
Here we specify the 1 minute for expiring the session. After 1 minute when we refresh the page it shows the session expire message. If we refresh the page before completing 1 minute then the session will not expire.
You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$20
For Premium members:
$45
For Elite members: