Session Management In ASP.NET Web API

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 on 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.

Example

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 Session Management in the Web API.

Step 1. Create the Web API application.

Create the Web API application using the following procedure.

  • Start Visual Studio 2012.
  • 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".
    Web Application
  • From the "MVC4 Project" window select "Web API".
    MVC4 Project

Step 2. Create a model class using the following procedure.

  • In the "Solution Explorer".
  • Right-click on the "Model folder"->"Add"->"Class".
  • Select "Installed"->"Visual C#" and select "Class".
    Solution Explorer
  • Click on the "OK" button.

Add the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SessionMgmt.Models
{
    public class SessionModel
    {
        public string UserName { get; set; }
        public string User_Pwd { get; set; }
        public string Session_Val { get; set; }
    }
}

Step 3. Now open the "HomeCOntroller" file using the following procedure.

  • In the "Solution Explorer".
  • Select "Controller" -> "HomeController".

Add the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SessionMgmt.Models;

namespace SessionMgmt.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(SessionModel info)
        {
            Session["UserId"] = info.UserName;
            return RedirectToAction("UserSessionSection");
        }

        public ActionResult UserSessionSection()
        {
            var Data_session = new SessionModel();
            try
            {
                if (Session["UserId"] != null)
                {
                    Data_session.Session_Val = "Welcome " + Session["UserId"].ToString();
                }
                else
                {
                    Data_session.Session_Val = "Session has been expired";
                }
            }
            catch
            {
                // Handle exception
            }
            return View(Data_session);
        }
    }
}

Step 4. Create a "UserSessionSection.cshtml" file using the following procedure.

  • In the "HomeController" file.
  • Right-click on the "UsersessionSection" Action then select "Add View".
    HomeController
    Add view
  • Click on the "OK" button.

Add the following code,

@model SessionMgmt.Models.SessionModel

@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>UserSection</title>
</head>
<body>
    <div style="width: 100%; height: 100px; background-color: lightyellow;">
    </div>
    <div style="width: 100%; height: 315px;">
        <h4>
            @Html.DisplayFor(a => a.Session_Val)
        </h4>
    </div>
    <div style="width: 100%; height: 200px; background-color: lightyellow;">
    </div>
</body>
</html>

Step 5. Now open the "index. cshtml" file using the following procedure.

  • In the "Solution Explorer".
  • Select "Views" -> "Home" -> "index. cshtml.

Add the following code,

@model SessionMgmt.Models.SessionModel

@{
    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: lightyellow;">
    </div>
    <div style="width: 100%; height: 325px;">
        <fieldset style="width: 250px; margin-left: 500px; margin-top: 100px;">
            <legend>User Login</legend>
            @using (Html.BeginForm())
            {
                <table>
                    <tr>
                        <td align="right">
                            User Name:
                        </td>
                        <td>
                            @Html.TextBoxFor(a => a.UserName)
                        </td>
                    </tr>
                    <tr>
                        <td align="right">
                            User Password:
                        </td>
                        <td>
                            @Html.PasswordFor(a => a.User_Pwd)
                        </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: 325px; background-color: lightyellow;">
    </div>
</body>
</html>

Step 6. Add the line of code in the Web. config file. It exists in the.

  • In the "Solution Explorer".
  • Select "web. config" file.
<system.web>
    <sessionState mode="InProc" timeout="1"></sessionState>
</system.web>

In this code, timeout="1" specifies that after 1 minute the session will expire. If we do not specify the time then by default the time for expiring the session is 20 minutes.

Step 7. Execute the application; press "F5".

Press F5

Enter the User Name and User Password and click on the submit button.

The output looks like this,

User Name

User Password

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.

Expire message


Similar Articles