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

OUTPUT :

The following “NullReferenceException” error occur when try to access โ€œIndexโ€ action method.

sessionstate in mvc -dotnet-helpers

Note:

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

 

Keep Cool Coding…