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

  • 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".

se7.jpg

  • From the "MVC4 Project" window select "Web API".

se8.jpg

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

se2.jpg

  • Click on the "OK"button.

Add the following code:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. namespace SessionMgmt.Models {  
  6.     public class SessionModel {  
  7.         public string UserName {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         public string User_Pwd {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         public string Session_Val {  
  16.             get;  
  17.             set;  
  18.         }  
  19.     }  
  20. }  

 

Step 3

Now open the "HomeCOntroller" file using the following procedure:

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

Add the following code:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using SessionMgmt.Models;  
  7. namespace SessionMgmt.Controllers {  
  8.     public class HomeController: Controller {  
  9.         public ActionResult Index() {  
  10.                 return View();  
  11.             }  
  12.             [HttpPost]  
  13.         public ActionResult Index(SessionModel info) {  
  14.             Session["UserId"] = info.UserName;  
  15.             return RedirectToAction("UserSessionSection");  
  16.         }  
  17.         public ActionResult UserSessionSection() {  
  18.             var Data_session = new SessionModel();  
  19.             try {  
  20.                 if ((Object) Session["UserId"] != null) Data_session.Session_Val = "Welcome  " + Session["UserId"].ToString();  
  21.                 else Data_session.Session_Val = "Session has been expired";  
  22.             } catch {}  
  23.             return View(Data_session);  
  24.         }  
  25.     }  

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

se.jpg


se1.jpg

  • Click on the "Ok" button.

Add the following code,

  1. @model SessionMgmt.Models.SessionModel   
  2.   
  3. @{  
  4.   
  5.     Layout = null;  
  6.   
  7. }  
  8.   
  9. <!DOCTYPE html>  
  10.   
  11. <html>  
  12.   
  13. <head>  
  14.   
  15.     <meta name="viewport" content="width=device-width" />  
  16.   
  17.     <title>UserSection</title>  
  18.   
  19. </head>  
  20.   
  21. <body>  
  22.   
  23.     <div style="width: 100%; height: 100px; background-color: lightyellow;">  
  24.   
  25.     </div>  
  26.   
  27.     <div style="width: 100%; height: 315px;">  
  28.   
  29.         <h4>  
  30.   
  31.        @Html.DisplayFor(a => a.Session_Val)          
  32. </h4>  
  33.   
  34.     </div>   
  35.   
  36.     <div style="width: 100%; height: 200px; background-color: lightyellow;">  
  37.   
  38.     </div>  
  39.   
  40. </body>  
  41.   
  42. </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,

  1. @model SessionMgmt.Models.SessionModel  
  2.   
  3. @{  
  4.   
  5.     Layout = null;  
  6.   
  7. }  
  8.   
  9. <!DOCTYPE html>  
  10.   
  11. <html>  
  12.   
  13. <head>  
  14.   
  15.     <meta name="viewport" content="width=device-width" />  
  16.   
  17.     <title>Index</title>  
  18.   
  19. </head>  
  20.   
  21. <body>  
  22.   
  23.     <div style="width: 100%; height: 100px; background-color: lightyellow;">  
  24.   
  25.     </div>  
  26.   
  27.     <div style="width: 100%; height: 325px;">  
  28.   
  29.         <fieldset style="width: 250px; margin-left: 500px; margin-top:100px;">  
  30.   
  31.             <legend>User Login </legend>  
  32.   
  33.             @using (Html.BeginForm())  
  34.   
  35.             {  
  36.   
  37.             <table>  
  38.   
  39.                 <tr>  
  40.   
  41.                     <td align="right";>  
  42.   
  43.                         User Name:  
  44.   
  45.                     </td>  
  46.   
  47.                     <td>  
  48.   
  49.                         @Html.TextBoxFor(a => a.UserName)  
  50.   
  51.                     </td>  
  52.   
  53.                 </tr>  
  54.   
  55.                 <tr>  
  56.   
  57.                     <td align="right";>  
  58.   
  59.                        User Password:  
  60.   
  61.                     </td>  
  62.   
  63.                     <td>  
  64.   
  65.                         @Html.PasswordFor(a => a.User_Pwd)  
  66.   
  67.                     </td>  
  68.   
  69.                 </tr>  
  70.   
  71.                 <tr>  
  72.   
  73.                     <td>  
  74.   
  75.                     </td>  
  76.   
  77.                     <td align="right";>  
  78.   
  79.                         <input id="btnLogin" type="submit" value="Login" />  
  80.   
  81.                     </td>  
  82.   
  83.                 </tr>  
  84.   
  85.             </table>  
  86.   
  87.             }  
  88.   
  89.         </fieldset>  
  90.   
  91.     </div>  
  92.   
  93.     <div style="width: 100%; height: 325px; background-color: lightyellow;">  
  94.   
  95.     </div>  
  96.   
  97. </body>  
  98.   
  99. </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.

  1. <system.web>  
  2. <sessionState mode="InProc" timeout="1">  
  3.   </system.web>  

 

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".
se3.jpg
Enter the User Name  and User Password and click on the submit button.

The output looks like this,
se4.jpg
se5.jpg

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.

se6.jpg

Similar Articles