Background
State management is a very important and useful concept in Web applications and it is equally very important that resources can not be allocated unnecessarily. In ASP.NET MVC we can manage the session controller specifically which helps to disable the session when you don't require IT for the 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 about how it will be possible ?, So it's possible with the help of the 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 the controller class which is used to control or manage the default session behavior. To use the session state attribute we need to use System.Web.SessionState namespace.
The following are the behavior of the Session State attribute.
- Default
- Disabled
- Required
- ReadOnly
Let's learn about them in brief.
Default
The default behavior of the session state checks for the session when the user request comes to the controller with the help of the IHttpHandler interface.
Example
[SessionState(SessionStateBehavior.Default)]
public class HomeController : Controller
{
// Action methods
}
Disabled
When SessionState behavior is set to disable then it will not check the session when a user request comes to the controller and it disabled the session for the 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 checks for the session and it enables the session for a particular controller. This behavior is used when you want a session for every user request.
Example
[SessionState(SessionStateBehavior.Required)]
// controller
public class HomeController : Controller
{
// Action methods
}
ReadOnly
When the Session state behavior is set to ReadOnly then the session state can not be modified and updated. This behavior is 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 understood the SessionState from the preceding brief summary. Now let's implement it practically, How to manage sessions at controller-specific.
Step 1. Create an MVC application.
- "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
- "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.
- Choose the MVC empty application option and click on OK
Step 2. Add model class.
Right-click on the Model folder in the created MVC application add a class named EmpModel and right the following lines of code.
EmpModel.cs
public class EmpModel
{
public string Name { get; set; }
}
Step 3. Add user and admin controller controller.
Right-click on the Controller folder in the created MVC application and add the controller class as,
Now after selecting the controller template, click on the add button then the following window appears.
Specify the controller name and click on the 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 a home controller and defined the SessionState attribute with Disabled behavior, and in the action method we are storing the 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 the view folder in the created MVC application and add a view named Index from the EmpModel class.
Now the form code automatically gets generated into the Index.cshtml view and modify it by writing the code to read the 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, an exception occurred because we disabled the session for this controller and tried to use the session, that's why the null reference exception occurred.
It is a good practice that there is no need to maintain the session for the specific controller in your application, then disable it which will really improve the performance of your application.
Now let us enable the session, and set the 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 is displayed because we have enabled the session at the controller level. I hope from all the preceding examples, you have learned how to set manage sessions 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 them in the comment section.