The SessionState Attribute helps us to control the session state behavior in ASP.NET MVC. Using properties like state Default/disable/read only, we can control the behavior for the controller. Sessions attribute is a class level so we can only apply at the controller not on action.

Problem with SessionState attribute

We can control session state behavior using Session State attribute but the main drawback is, this can only be applied at the controller level not at the action level. So all action methods inside the controller have the same session state behavior. In some scenario, the action methods of the controller need not to use session behavior. !!

How to over come ?

Bad Practice:

In this scenario, we will think to create a different controller and move all the action methods based on the same behavior. But this is not a good practice.

Good Practice:

Instead of moving an action method to the other controller, we can create a custom action attribute that overwrites the behavior of the session state for the specific action method.

Session State Behaviour:

The SessionState attribute in MVC provide control the behavior of the session state by accessing the value of the behavior property.

SessionStateBehavior.Default– It is a default logic, used to determine the session state behavior for the request.
SessionStateBehavior.Required – Here read-write session state behaviour is enabled.
SessionStateBehavior.ReadOnly – Read only session state is enabled.
SessionStateBehavior.Disabled – Session state is not enabled for processing (session state will be disabled).

Example code


The following “NullReferenceException” error occur when try to access “Index” action method.

sessionstate in mvc -dotnet-helpers


  • In MVC3 (Beta) SessionState() attribute was refereed as ControllerSessionState()


Keep Cool Coding…