Manage Controller Specific Session In ASP.NET MVC 5

Background

State management is very important and useful concept in Web application and also its equally very important that resources can not be allocated unnecessarily. In ASP.NET MVC we can manage the session controller specific which helps to disable the session when you don't require IT for particular controller and due to this we can improve the performance of an application by freeing resources not needed to be allocated. Now you might be thinking that how it will be possible ?, So its possible with the help of controller attribute SessionState.

Now let us learn about the SessionState attribute in brief so it will be useful to understand easily.
 
What is SessionState

Session State is the attribute of controller class which is used to control or manage the default session behavior.To use session state attribute we need to use System.Web.SessionState namespace.

The following are the behavior of the Session State attribute 
  1. Default
  2. Disabled
  3. Required
  4. ReadOnly

Let's learn about them in brief,

  • Default

    The default behavior of the session state checks for the session when user request comes to the controller with the help of IHttpHandler interface.

    Example
    1. [SessionState(SessionStateBehavior.Default)]    
    2.   public class HomeController : Controller    
    3.   {    
    4.       // Action methods     
    5.         
    6.   }   
  • Disabled

    When SessionState behavior set to disable then it will not check the session when user request comes to the controller and it disabled the session for entire controller and their views .

    This property is very important when you want to disable the session for controller specific where there is no need to maintain the session.

    Example:
    1. [SessionState( SessionStateBehavior.Disabled)]    
    2. //controller     
    3. public class HomeController : Controller    
    4. {    
    5.     // Action methods    
    6.      
    7. }    
  • Required

    When the behavior is set to required then every request check for the session and it enabled the session for particular controller. This behavior is used when you want session for every user request.

    Example
    1. [ SessionState( SessionStateBehavior.Required)]    
    2. //controller     
    3. public class HomeController : Controller    
    4. {    
    5.     // Action methods    
    6.       
    7. }   
  • ReadOnly

    When Session state behavior set to ReadOnly then session state can not be modified and updated. This behavior useful to make sure the session state will not be modified.

    Example
    1. [ SessionState( SessionStateBehavior.ReadOnly)]    
    2. //controller     
    3. public class HomeController : Controller    
    4. {    
    5.     // Action methods    
    6.       
    7. }   

I hope you have understand about the SessionState from preceding brief summary. Now let's implement it practically, How to manage session at controller specific

Step 1 :
Create an MVC application.

  1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".

  2. "File", then "New" and click "Project" then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK.

  3. Choose MVC empty application option and click on OK

Step 2: Add model class.

Right click on Model folder in the created MVC application and add class named EmpModel and right the following lines of code as.

EmpModel.cs
  1. public class EmpModel    
  2. {    
  3.    public string Name { getset; }    
  4. }     
Step 3: Add user and admin controller controller.

Right click on Controller folder in the created MVC application and add the controller class as:

Now after selecting controller template, click on add button then the following window appears,

 
Specify the controller name and click on add button, Now open the HomeController.cs file and write the following code into the Home controller class as:

HomeController.cs
  1. using System;  
  2. using System.Web.Mvc;  
  3. using SessionStateAttributeInMVC.Models;  
  4. using System.Web.SessionState;  
  5.   
  6. namespace SessionStateAttributeInMVC.Controllers  
  7. {  
  8.     [ SessionState( SessionStateBehavior.Disabled)]  
  9.     public class HomeController : Controller  
  10.     {  
  11.         // GET: Home  
  12.         public ActionResult Index()  
  13.         {  
  14.             return View();  
  15.         }  
  16.         [HttpPost]  
  17.         public ActionResult Index(EmpModel obj)  
  18.         {  
  19.             //store the session from user input and display into the view if session is enabled.  
  20.             Session["Name"] = Convert.ToString(obj.Name);  
  21.             return View();  
  22.   
  23.         }  
  24.     }  

In the above code , We have created home controller and defined SessionState attribute with Disabled behavior and in Post action method we are storing user input value into session and returning to the index view where we will display the session value.
 
Step 4: Add strongly typed view as:

Right click on view folder in the created MVC application and add view named Index from EmpModel class as.
 
 

Now the form code automatically get generated into the Index.cshtml view and modify it by writing the code to read session value if the session is enabled. After modifying the code, view.cshtml source code will be like the following,
  1. @model SessionStateAttributeInMVC.Models.EmpModel  
  2.   
  3. @{  
  4.     ViewBag.Title = "www.compilemode.com";  
  5. }  
  6. @using (Html.BeginForm())  
  7. {  
  8.     @Html.AntiForgeryToken()  
  9.   
  10.     <div class="form-horizontal">  
  11.         <h4>EmpModel</h4>  
  12.         <hr />  
  13.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
  14.         <div class="form-group">  
  15.             @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
  16.             <div class="col-md-10">  
  17.                 @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })  
  18.                 @Html.ValidationMessageFor(model => model.Name, ""new { @class = "text-danger" })  
  19.             </div>  
  20.         </div>  
  21.         @if (Session["Name"] != null)  
  22.         {  
  23.             //if session is enabled then display the session value  
  24.   
  25.             @Html.Label(Convert.ToString(Session["Name"]), htmlAttributes: new { @class = "control-label col-md-4" })  
  26.   
  27.         }  
  28.         <div class="form-group">  
  29.             <div class="col-md-offset-2 col-md-10">  
  30.                 <input type="submit" value="Create" class="btn btn-default" />  
  31.             </div>  
  32.         </div>  
  33.     </div>  

Now run the application and the following error will occur.
 
 

In the above null reference exception occur because we disabled the session for this controller and tried to use session, that's why the null reference exception occurred.

It is a good practice that there is no need to maintain the session for specific controller in your application, then disable it which will really improve the performance of your application.

Now let us enable the session, set Session state behavior to default as:
  1. using System;    
  2. using System.Web.Mvc;    
  3. using SessionStateAttributeInMVC.Models;    
  4. using System.Web.SessionState;    
  5.     
  6. namespace SessionStateAttributeInMVC.Controllers    
  7. {    
  8.     [ SessionState( SessionStateBehavior.Default)]    
  9.     public class HomeController : Controller    
  10.     {    
  11.         // GET: Home    
  12.         public ActionResult Index()    
  13.         {    
  14.             return View();    
  15.         }    
  16.         [HttpPost]    
  17.         public ActionResult Index(EmpModel obj)    
  18.         {    
  19.             //store the session from user input and display into the view if session is enabled.    
  20.             Session["Name"] = Convert.ToString(obj.Name);    
  21.             return View();    
  22.     
  23.         }    
  24.     }    
  25. }   
Now run the application and input some value into the textbox, then it will get back displayed using session in view as:
 
 

The above output get displayed because we have enabled the session at controller level. I hope from all the preceding examples, you have learned how to set manage session at controller specific in ASP.NET MVC. 

Note:
  • Download the Zip file of the sample application for a better understanding.
  • Apply proper validation before using it in your project.
Summary

I hope this article is useful for all readers. If you have any suggestions, then please mention it in the comment section.  

Up Next
    Ebook Download
    View all
    Learn
    View all