Session Management in ASP.NET MVC

.Net Developer
3 min readJan 1, 2020

HTTP is a stateless protocol; this protocol cannot store user information on the server-side as per user basis because Web server treats each HTTP request for a page as an independent request. No server has knowledge of any kind of variable value. ASP.NET MVC Session state enables you to store and retrieve values for a user when the user navigates another view in an ASP.NET MVC application. The session is defined as the period of time that a unique user interacts with a Web application.

In this article, I tell you how to pass data from one view to another in ASP.NET MVC using session and also I tell you how to manage login user information using session. Steps are given below

Step 1: First create a model class and some properties as below

Step 2: Create two actions within the controller (e.g. Home controller) as below

Write the line of code for index view as below

Write a line of code for EmployeeSection view as below

Set session expired time value on web.config page as below : Here timeout=”5", indicate session expired time is 5 minutes. If we do not specify session time out value than session default expired time is 20 minutes.

if you want to do something after session expired then write a line of code within the Session_End method in Global.asax.cs as below

Build and Save application and press F5 for execution and see screenshot as below image

Here this is a simple demo, so I’m not checking any authentication for login. I’m simple store user id into session and pass to another view (e.g. EmployeeSection). When you click on the Login button and see EmployeeSection view UI as below image

Wait for 5 minutes, if you do not refresh the page within 5 minutes (in this demo) then after 5 minutes session expired and when next time you refresh the page, session expired message display as below image.

Session expires time to start to count, when you did not do anything after login.

Last updated:7/29/2020 7:07:13 AM

Originally published at https://www.mindstick.com on January 1, 2020.

--

--

.Net Developer

I’m a professional Technical writer and Software Development with more than 5 years of experience.