Session-less Controllers in ASP.NET MVC 3 RC
Posted by: Malcolm Sheridan
in Category ASP.NET MVC
Abstract: The following article demonstrates the new session-less controllers in ASP.NET MVC 3 RC.
Microsoft has just released ASP.NET MVC 3 Release Candidate. The razor view engine is certainly the biggest addition to the framework, but one feature that has been long overdue in my opinion is the ability to have session-less controllers. There have been numerous times when I wanted this and had to use workarounds. Now this has been added and I’ll show you how to use it..
Before moving on, you need to download ASP.NET MVC 3 Release Candidate (RC). Click here to download and install them using the Microsoft Web Platform Installer. Likewise you can download it from the website here.
Open studio 2010 and create a new ASP.NET MVC 3 Web Application (Razor) project. The new MVC 3 RC dialog can be seen below. Choose an Empty template and select Razor as the view engine and click OK.
Add a new controller to the project. Controlling the session in the controller is as simple as decorating the controller with the ControllerSessionState attribute. This specifies the type of session support for the controller. Here's the code to create a session-less controller.
ControllerSessionState accepts a SessionStateBehaviour enum. This parameter specifies the type of session support for a controller. The possible values for this are:
Disabled - session state is not enabled for processing the request
Default - the default ASP.NET logic is used to determine the session state behaviour for the request
ReadOnly - read-only session state is enabled for the request
Required - full read-write session state is enabled for the request
It's important to remember that if you have a session-less controller, using TempData will not work because the default store for TempData is the session. So doing the following will throw an exception.
Note: As pointed by Anders in the comments section, in the final version of MVC3 the attribute is (re)named: [SessionState(SessionStateBehavior.Disabled)]
The code above will throw an exception because the session has been disabled for the controller. The exception thrown is:
The SessionStateTempDataProvider class requires session state to be enabled.
For me this functionality has been long overdue and I'm very happy it has been included in MVC 3 RC. This will be one feature you will use often.
The entire source code of this article can be downloaded over here.