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 ?
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.
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).
[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;
The following “NullReferenceException” error occur when try to access “Index” action method.
- In MVC3 (Beta) SessionState() attribute was refereed as ControllerSessionState()
Keep Cool Coding…