Shravan Kumar Kasagoni

Skip Navigation

How to Create Sessionless Controller in MVC3

 /  Leave a response

How to manage the controller’s session state?

Simply we can decorate the controller class with ‘SessionState’ attribute. [SessionState()] attribute accepts SessionStateBehaviour enumeration.

SessionStateBehaviour enumeration has the following constants:

  • SessionStateBehavior.Default– ASP.NET default logic is used to determine the session state behaviour for the request.
  • SessionStateBehavior.Required – Full read-write session state behaviour is enabled for the request.
  • SessionStateBehavior.ReadOnly – Read only session state is enabled for the request.
  • SessionStateBehavior.Disabled – Session state is not enabled for processing the request.
using System.Web.Mvc;
using System.Web.SessionState;

namespace MvcTestApp1.Controllers
{
    [SessionState(SessionStateBehavior.Disabled)]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}

We decorated controller class with [SessionState(SessionStateBehaviour.Disabled)] to disable the session. Important point to remember when we are disabling session of the controller, we should not use TempData[] Dictionary to store any values with action method controller, it uses session to store it’s values. If you use TempData[] Dictionary when session is disabled on controller it will throw an exception "The SessionStateTempDataProvider class requires session state to be enabled".

Note: In earlier release of MVC3 (Beta) [SessionState()] attribute was refereed as [ControllerSessionState()]

Write a response

Your email address will not be published. Required fields are marked *

All code will be displayed literally.