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

Session Management in ASP.NET MVC


ASP.NET MVC ASP.NET MVC 
Ratings:
2 Comment(s)
 82712  View(s)
Rate this:

Session Management in ASP.NET MVC

HTTP is stateless protocol; this protocol cannot store user information on server side as per user basis because Web server treats each HTTP request for a page as an independent request. The server retains no knowledge of variable values. ASP.NET MVC Session state enables you to store and retrieve values for a user when user navigates other view in an ASP.NET MVC application. A 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 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 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 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 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 in 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 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 line of code within 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 screen shot as below image

Session Management in ASP.NET MVC

Note: Here this is 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 Login button and see EmployeeSection view UI as below image

Session Management in ASP.NET MVC

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

Session Management in ASP.NET MVC

Note: Session expire time start count, when you not do anything after login.  


very nice

By Yogesh kumar on   4 months ago


good article

By Andrew Tappert on   3 months ago
Though the title made me think it was going to be about managing session, rather than using session to do useful things with data.  -cheers!

Don't want to miss updates? Please click the below button!

Follow MindStick