Manage Controller Specific Session In ASP.NET MVC

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
[SessionState(SessionStateBehavior.Default)]    
  public class HomeController : Controller    
  {    
      // Action methods     
        
  }
  • 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:
[SessionState( SessionStateBehavior.Disabled)]    
//controller     
public class HomeController : Controller    
{    
    // Action methods    
     
} 
  • 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
[ SessionState( SessionStateBehavior.Required)]    
//controller     
public class HomeController : Controller    
{    
    // Action methods    
      
}  
  • 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
[ SessionState( SessionStateBehavior.ReadOnly)]    
//controller     
public class HomeController : Controller    
{    
    // Action methods    
      
} 
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
public class EmpModel    
{    
   public string Name { get; set; }    
}  
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
using System;  
using System.Web.Mvc;  
using SessionStateAttributeInMVC.Models;  
using System.Web.SessionState;  
  
namespace SessionStateAttributeInMVC.Controllers  
{  
    [ SessionState( SessionStateBehavior.Disabled)]  
    public class HomeController : Controller  
    {  
        // GET: Home  
        public ActionResult Index()  
        {  
            return View();  
        }  
        [HttpPost]  
        public ActionResult Index(EmpModel obj)  
        {  
            //store the session from user input and display into the view if session is enabled.  
            Session["Name"] = Convert.ToString(obj.Name);  
            return View();  
  
        }  
    }  
}  
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,
@model SessionStateAttributeInMVC.Models.EmpModel  
  
@{  
    ViewBag.Title = "www.compilemode.com";  
}  
@using (Html.BeginForm())  
{  
    @Html.AntiForgeryToken()  
  
    <div class="form-horizontal">  
        <h4>EmpModel</h4>  
        <hr />  
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
        <div class="form-group">  
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })  
            </div>  
        </div>  
        @if (Session["Name"] != null)  
        {  
            //if session is enabled then display the session value  
  
            @Html.Label(Convert.ToString(Session["Name"]), htmlAttributes: new { @class = "control-label col-md-4" })  
  
        }  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10">  
                <input type="submit" value="Create" class="btn btn-default" />  
            </div>  
        </div>  
    </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:
using System;    
using System.Web.Mvc;    
using SessionStateAttributeInMVC.Models;    
using System.Web.SessionState;    
    
namespace SessionStateAttributeInMVC.Controllers    
{    
    [ SessionState( SessionStateBehavior.Default)]    
    public class HomeController : Controller    
    {    
        // GET: Home    
        public ActionResult Index()    
        {    
            return View();    
        }    
        [HttpPost]    
        public ActionResult Index(EmpModel obj)    
        {    
            //store the session from user input and display into the view if session is enabled.    
            Session["Name"] = Convert.ToString(obj.Name);    
            return View();    
    
        }    
    }    
}    
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. 

Post a Comment

www.CodeNirvana.in

Protected by Copyscape Online Copyright Protection
Copyright © Compile Mode