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 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.     }    
  26. } 
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.     Layout = null;  
  4. }  
  5. <!DOCTYPE html>  
  6. <html>  
  7. <head>  
  8.     <meta name="viewport" content="width=device-width" />  
  9.     <title>UserSection</title>  
  10. </head>  
  11. <body>  
  12.     <div style="width: 100%; height: 100px; background-color: lightyellow;">  
  13.     </div>  
  14.     <div style="width: 100%; height: 315px;">  
  15.         <h4>  
  16.        @Html.DisplayFor(a => a.Session_Val)            
  17. </h4>  
  18.     </div>  
  19.     <div style="width: 100%; height: 200px; background-color: lightyellow;">  
  20.     </div>  
  21. </body>  
  22. </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.     Layout = null;  
  4. }  
  5. <!DOCTYPE html>  
  6. <html>  
  7. <head>  
  8.     <meta name="viewport" content="width=device-width" />  
  9.     <title>Index</title>  
  10. </head>  
  11. <body>  
  12.     <div style="width: 100%; height: 100px; background-color: lightyellow;">  
  13.     </div>  
  14.     <div style="width: 100%; height: 325px;">  
  15.         <fieldset style="width: 250px; margin-left: 500px; margin-top:100px;">  
  16.             <legend>User Login </legend>  
  17.             @using (Html.BeginForm())  
  18.             {  
  19.             <table>  
  20.                 <tr>  
  21.                     <td align="right";>  
  22.                         User Name:  
  23.                     </td>  
  24.                     <td>  
  25.                         @Html.TextBoxFor(a => a.UserName)  
  26.                     </td>  
  27.                 </tr>  
  28.                 <tr>  
  29.                     <td align="right";>  
  30.                        User Password:  
  31.                     </td>  
  32.                     <td>  
  33.                         @Html.PasswordFor(a => a.User_Pwd)  
  34.                     </td>  
  35.                 </tr>  
  36.                 <tr>  
  37.                     <td>  
  38.                     </td>  
  39.                     <td align="right";>  
  40.                         <input id="btnLogin" type="submit" value="Login" />  
  41.                     </td>  
  42.                 </tr>  
  43.             </table>  
  44.             }  
  45.         </fieldset>  
  46.     </div>  
  47.     <div style="width: 100%; height: 325px; background-color: lightyellow;">  
  48.     </div>  
  49. </body>  
  50. </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