Session State Behavior Per Action in ASP.NET MVC

The SessionState Attribute helps us to controll the session state behavior in ASP.NET MVC. We can make session state disable / read only / required for controller using this attribute. This is a class level attribute so we can only apply this attribute at the controller level. Some of the action methods of a controller might have a different behavior than the controller session state behavior. In this case the following solution is very useful. So we can apply a session state behavior per action in ASP.NET MVC.

Problem Statement

We can control session state behavior using SessionState attribute but this can only be applied at the controller level. This means that all action methods of the controller have the same session state behavior. Now if some of the action methods of the controller do not use a session and some of action method does use the session then what is solution?

Solution

In this scenario, we can create a different controller and move all the action methods that have the same session state behavior for in the same controller class. This is not a good solution. Instead of doing this we can create a custom action attribute that overwrites the behavior of the session state for the specific action method.

Use the following procedure to create a custom action attribute that overrides the behavior of the session state.

We can use the ActionSessionStateAttribute in combination with the controller level attribute SessionStateAttribute, in this case use the ActionSessionStateAttribute overwrite controller attribute on the actions to which it applies.