21
NovControlling Session Behavior in Asp.Net MVC4
Controlling Session: An Overview
By default, Asp.Net MVC support session state. The session is used to store data values across requests. Whether you store some data values within the session or not Asp.Net MVC must manage the session state for all the controllers in your application which is time-consuming. Since the session is stored on the server side and consumes server memory, hence it also affects your application performance. In this MVC Tutorial, we will explore more about Session state in MVC, disable session in mvc, session-less controller, and session-less action method. Consider our ASP.NET MVC Course for a better understanding of all MVC core concepts.
Session state in MVC
It provides more control over the behavior of the session state by specifying the value of the behavior property If it is a read-only property we can set it using a parameterized contractor of the SessionStateAttribute.
Session Less Controller
If some of the controllers of your Asp.Net MVC application are not using session state features, you can disable session for that controller and can gain slight performance improvement of your application. You can simplify the session state for your application by using available options for session state.
In Asp.Net MVC4, the SessionState attribute provides you more control over the behavior of the session-state by specifying the value of SessionStateBehavior enumeration as shown below:
SessionStateBehavior Enumeration's Value
In Asp.Net MVC, TempData uses a session state for storing the data values across requests. Hence, when you disable the session state for the controller, it will throw the exception as shown below:
Session-State Modes
- In-Process Mode
- State Server Mode
- SQL Server Mode
- Custom Mode
In-Process Mode
- It is the default session state mode.
- It is specified using the InProc SessionStateMode enumeration value.
- It stores session state values.
- Variables in memory on the local Web server.
- It is the only mode that supports the Session_OnEnd event.
- For more information about the Session_OnEnd event, see Session-State Events.
State Server Mode
- It stores the session state in a process.
- It is referred to as the ASP.NET state service, which is separate from the ASP.NET worker process or IIS application pool.
- It ensures that the session state is preserved if the Web application is restarted
- It makes the session state available to multiple Web servers in a Web farm.
SQL Server Mode
- It stores the session state in an SQL Server database.
- Using this mode ensures that the session state is preserved if the Web application is restarted.
- It also makes the session state available to multiple Web servers in a Web farm.