articles

Home / DeveloperSection / Articles / Session Management in ASP.NET MVC

Session Management in ASP.NET MVC

Session Management in ASP.NET MVC

AVADHESH PATEL 140668 24-Jan-2013

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

 

namespace SessionAspDotNetMvc.Models

{
    /// <summary>
    /// Class with three properties
    /// </summary>
    public class SessionAspDotNetMvcModel
    {
        // property for set user's id
        public string sUserID
        {
            get;
            set;
        }
 
        // property for set user's password
        public string sPassword
        {
            get;
            set;
        }
 
        // property for set session value
        public string sSessionValue
        {
            get;
            set;
        }
    }
}

 

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

 

using System;

using System.Web.Mvc;
// Added model namespace
using SessionAspDotNetMvc.Models;
 
 
namespace SessionAspDotNetMvc.Controllers
{
    public class HomeController : Controller
    {
        ///<summary>
        /// Default action name
        ///</summary>
        ///<returns></returns>
        public ActionResult Index()
        {
            return View();
        }
 
        ///<summary>
        /// Second action where we receive session value
        ///</summary>
        ///<param name="data"></param>
        ///<returns></returns>
        [HttpPost]
        public ActionResult Index(SessionAspDotNetMvcModel data)
        {
            // Assign value into session
            Session["SessionUserID"] = data.sUserID;
            // Redirect view
            return RedirectToAction("EmployeeSection");
        }
 
        public ActionResult EmployeeSection()
        {
            // Create object of model call for call properties and set value
            var vSessionValue = new SessionAspDotNetMvcModel();
            try
            {
                // check existing value into session
                if ((Object)Session["SessionUserID"] != null)
                    // assign value into properties
                    vSessionValue.sSessionValue = "Welcome " +
 Session["SessionUserID"].ToString();
                else
                    // if session expired than set custom message
                    vSessionValue.sSessionValue = "Session Expired";
            }
            catch
            {
 
            }
            // return value to view
            return View(vSessionValue);
        }
    }
}

  Step 3: Write the line of code for index view as below

@model SessionAspDotNetMvc.Models.SessionAspDotNetMvcModel

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div style="width: 100%; height: 100px; background-color: LightBlue;">
    </div>
    <div style="width: 100%; height: 315px;">
        <fieldset style="width: 250px; margin-left: 500px; margin-top:100px;">
            <legend>Login </legend>
            @using (Html.BeginForm())
            {
            <table>
                <tr>
                    <td align="right";>
                        User ID:
                    </td>
                    <td>
                        @Html.TextBoxFor(m => m.sUserID)
                    </td>
                </tr>
                <tr>
                    <td align="right";>
                        Password:
                    </td>
                    <td>
                        @Html.PasswordFor(m => m.sPassword)
                    </td>
                </tr>
                <tr>
                    <td>
                    </td>
                    <td align="right";>
                        <input id="btnLogin" type="submit" value="Login" />
                    </td>
                </tr>
            </table>
            }
        </fieldset>
    </div>
    <div style="width: 100%; height: 100px; background-color: LightBlue;">
    </div>
</body>
</html>

 Write a line of code for EmployeeSection view as below

@model SessionAspDotNetMvc.Models.SessionAspDotNetMvcModel

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>EmployeeSection</title>
</head>
<body>
    <div style="width: 100%; height: 100px; background-color: LightBlue;">
    </div>
    <div style="width: 100%; height: 315px;">
        <h4>
       @Html.DisplayFor(m => m.sSessionValue) </h4>
 
    </div>
    <div style="width: 100%; height: 100px; background-color: LightBlue;">
    </div>
</body>
</html>

  Step 4: Set session expired time value on web.config page as below

<system.web>

    <sessionState mode="InProc" timeout="5" />
  </system.web>

Note: 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. 

Step 5: 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

 

/// <summary>

        /// This method execute when session time expired
        /// </summary>
        protected void Session_End()
        {
            // do somthing here
        }

 

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

Session Management in ASP.NET MVC

Note: 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

Session Management in ASP.NET MVC

Step 7: 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 Management in ASP.NET MVC

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


Updated 29-Jul-2020
Avadhesh Kumar Patel District Project Manager - Aligarh 14 months work experience in Panchayati Raj Department Sector as District Project Manager & 12 months work experience in IT Sector as Software Engineer. :-)

Leave Comment

Comments

Liked By