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
1 2 3 4 5 6 7 8 9 10 11 |
[fusion_builder_container hundred_percent="yes" overflow="visible"][fusion_builder_row][fusion_builder_column type="1_1" background_position="left top" background_color="" border_size="" border_color="" border_style="solid" spacing="yes" background_image="" background_repeat="no-repeat" padding="" margin_top="0px" margin_bottom="0px" class="" id="" animation_type="" animation_speed="0.3" animation_direction="left" hide_on_mobile="no" center_content="no" min_height="none"][SessionState(SessionStateBehavior.Disabled)] public class SessionlessController : Controller { // GET: Sessionless public ActionResult Index() { Session["sessionStr"] = DateTime.Now; return View(); } } |
OUTPUT :
The following “NullReferenceException” error occur when try to access โIndexโ action method.
Note:
- In MVC3 (Beta) SessionState() attribute was refereed as ControllerSessionState()
Keep Cool Coding…
Leave A Comment