1. Application State
In asp.net platform, application state is the place to store data is common to all components in the application and is shared between all requests. The application state can improve the performance of an application, since it normally store data or objects that you need frequently and resource-expensive to create for every request. However, it is also easy to create the opposite effect and slow down the system.
1.1 user applicaiton state
Application state is implemented by the HttpApplicationState class, that is defined in System.Web namespaces. And it is available through HttpContext.Application property.
members | description |
Add(key,value) | add a value to application with the specified key |
AllKeys | return the collection keys as a string array |
Clear() | remove application state data |
Count | return the number of state data items |
Lock() | acquires exclusive access to the application state data |
Item[index] | returns the item with specified index |
Item[key] | retruns the item with specified key |
Remove(key) | remove the value with specified key |
Remove(index) | remove the value with specified index |
unLock() | release exclusive access to the application state data |
Let‘s look at one example of using application state.
public static object Get(HttpApplicationState appState, AppStateKeys key, object defaultValue = null) { var keyString = Enum.GetName(typeof (AppStateKeys), key); if (appState[keyString] == null && defaultValue != null) { appState[keyString] = defaultValue; } return appState[keyString]; } public static void Set(HttpApplicationState appState, AppStateKeys key, object value) { appState[Enum.GetName(typeof (AppStateKeys), key)] = value; }
I wrapped the logic of handling application state into one utility class, which is easy for unit testing and improves the code reusability.
1.2 Understanding the synchronization effect
Asp.net processes requests concurrently, and to ensure that one request is trying to read data that another is trying to modify at the same time, the methods and properties of the HttpApplicationState class are synchronized.
All of the requests can read the data without delay. However, it needs to wait while trying to modify the data, to ensure the current operations have completed.
The performance of synchronization on performance depends on the number of concurrent requests that the application processes, the ratio of read to modification. When you dealing with real project, you will have to decide whether the conventience of being able to share data through HttpApplicationState is worth the performance penalty.
1.3 Performing related operations
The caution must be taken while you are working multiple related values,
The lock method defined in HttpApplicationState provides the exclusive access to the state data collection until the Unlock is called.
public static void SetMultiple(HttpApplicationState appState, IDictionary<AppStateKeys, object> data) { appState.Lock(); foreach (var key in data.Keys) { var keyString = Enum.GetName(typeof (AppStateKeys), key); appState[keyString] = data[key]; } appState.UnLock(); }
2. Sessionn State
Even http is a stateless protocol, it is sometimes necessary to identify related request in order to delivery continuity in web applications. Asp.net platform support session and session state, which allows requests from the same browser to be identified.
2.1 Working with session data
Session state is accessed through HttpContext.Session property, which returns System.Web.SessionState.HttpSessionState class.
HttpSessionState members:
Count | Returns the number of session state data items |
IsReadOnly | Return true if the session state data cannot be modified. |
IsSynchronized | Returns true if the session state data is synchronized |
Item[Index] | Fetch state data at the specified index |
Item[key] | Fetch state data at the specified key |
Clear() | Remove all state data item |
Remove(key) | Remove state data at the specified key |
Remove(index) | Remove state data at the specified index |
2.2 how session works
The entry point of the session feature is a module called SessionStateModule, which handles the AcquireRequestState request life-cycle event and is responsible for associating state data with request.
It looks for a session identifier in each request. The identifier is usually a cookie, and it is used to load the state data into HttpSessionState object which is attached to the HttpContext object associated with the request.
Abandon() | Terminates the current session |
CookieMode | it describes how sessions are identified |
IsCookieless | returns true if identification is performed without cookies |
IsNewSession | returns true if the session has been created during the current request |
Mode | describe how session state data is stored |
SessionID | return the identifier of the current session |
Timeout | the default is 20 |
The life of a session starts when a request arrives that doesn‘t contain a session cookie. At that time, HttpSessinoState.IsNewSession is true, and a new session identifier is created and assigned to the HttpSessionState.SessionID.
Asp.net platform will not add cookie to the response, if there is no session data.
2.3 Synchronization effect
ASP.NET processes multiple requests concurrently, and modern browser can make multiple requests concurrently.
So, there is a rick of data corruption.
To avoid the risk, asp.net froces request that come from the same session to execute sequentically. However, it slows down the processing of request, even when the request will not modify the session data at all.
2.4 controlling session state
The solution to the problem is to apply SessionState attribute.
[SessionState(SessionStateBehavior.Disabled)]
Default | |
Disabled | SessionState is disabled for the controller, the requests will be processed concurrently. Attempting to access state will result in an exception |
ReadOnly | The controller will be able to read session state data, but not modify. |
Required | It will cause request to execute sequentially. |
2.5 Configure session and session state
The session feature is configured through sessionState section in the web.config file.
ASP.net platform identified sessions with a cookie, relying on the browser to include it in the request sending to the server. In case cookies is disabled, asp.net provides us with other means of passing session id, such as url.
(Session.CookieMode) - AutoDetect, UseCookie, UseDeviceProfile, UseUri
<System.Web>
<sessionState cookieless="UseUri" />
</System.Web>
2.6 Storing session data
By default, session state data is stored in memory within processes. But, asp.net does have two other storage options.
InProc | This is default value, and store session data in process |
off | Disables sessions for the entire application |
SQLServer | The state data will be stored in database. |
StateServer | The state data will be stored in a dedicated server process. |
Custom |
2.7 state server
The asp.net platform comes with a separate server that can be used to store session state. The advantage is that you can host the session on a dedicate machine, and it won‘t lost when the application is stopped.
Be remember, the session data is still stored in memory, just the memory of another process, can can run on another server. The state server is only userful if you have a lot of state data.
The state server is a windows service that is installed as part of .net framework.
<sessionState cookieless="UseCookie" mode="StateServer" />
2.8 user sql database
Using a database to store session data ensures taht data isn‘t lost when a process is restarted.