Client Side State Management
| Viewstate |
Hashed by default to avoid tampering. Encrypted with ViewStateEncryptionMode="Always" in either web.config or page declarative.
Control.EnableViewState can be set to false to but controls can still use ControlState.
ViewState["someData"] = "something";
|
| Hidden Fields | |
| Cookies |
Response.Cookies.Add(new HttpCookie("userPrefs", userPrefs));
Response.Cookies["userPrefs"].Expires = DateTime.Now.AddDays(1);
Response.Cookies["userPrefs"].Path = "/SubDirLimitedScope";
Response.Cookies["userPrefs"].Domain = "contoso.com"; //Cookie submitted to all subdomains of contoso.com
Request.Cookies["userPrefs"].Value;
Request.Cookies["userPrefs"]["pref1"].Value;
Request.Cookies["userPrefs"]["pref2"].Value;
|
| Query Strings |
Request.QueryString["q"]
|
Server Side State Management
Application Global.asax Events
| Application_Start |
Application["UsersOnline"] = 0;
|
| Application_End | |
| Application_Error | Uncaught exception handling. |
| Application_LogRequest | For custom logging. |
| Application_PostLogRequest | |
| Application_BeginRequest | |
| Application_EndRequest | |
| Session_Start |
Application.Lock();
Application["UsersOnline"] = (int)Application["UsersOnline"] + 1;
Application.UnLock();
|
| Session_End |
Application.Lock();
Application["UsersOnline"] = (int)Application["UsersOnline"] - 1;
Application.UnLock();
When session state is InProc, this is raised when the session is abandoned or times out (timeout is a setting for the sessionState node in the web.config). However is not raised for other state modes. |
Session State
if(Session["lastRequestTime"] != null) {
DateTime lastRequestTime = (DateTime)Session["lastRequestTime"];
}
A cookie called ASP.NET_SessionId is written to the client with a random 24-byte value to track the user's session back to the server.
If session state not used, improve performance by disabling session state with sessionState mode="off" in the web.config or EnableSessionState = "False" in the page declarative.
Cookieless session state can be enabled by adding cookieless="true" to the web.config sessionState node above which will put the session id into url requests.
Session State Mode
| InProc | (Default) Session stored in memory on the web server. Best performance however you are restricted to "sticky" load balancing which isn't the best if one server goes down or you need to take one down. |
| StateServer | Stores session state in the ASP.NET State Service of a dedicated machine. |
| SQLServer | Slightly slower than state server unless database machine has powerful specifications. Gives more robust data integrity and reporting options. |
| Custom | Need to implement code for the custom storage provider. |
| Off | |