Translate

Sunday, February 27, 2011

ASP.NET State Management Overview


What is a State?

In plain and simple terms state is data/information. When you log into facebook,  have you ever wondered what happens when you check the "keep me logged in" box? How does it automatically sign in the next time you come back and type facebook.com? The answer is, when you click that checkbox facebook stores who you are in a cookie in your computer. Cookie is one of the many ways state/information is stored by a website.














When you build your website you store the state in either the client's computer or in your web server. Figure 1 below shows how state management can be classified in asp.net.


Figure 1. Asp.net state management overview









Both client side and server side state management have their own advantages and drawbacks. Lets look at these in a little bit more detail.


Client side state management

Let me start by stating that never store any kind of sensitive information on the client. Definitely not in plain text. 

Cookie:  Every browser (ie, chrome, firefox etc) have their own folders for storing cookies. Cookies are used for storing a variety of site specific data. Most commonly cookies are used to store your identity when you log into a website. The identity/token is stored usually in an encrypted/hashed format . For every GET/POST request, all the cookies generated by that domain, is sent to that server. The browser allows 20 cookies from a single server and all together (from all the servers) a maximum of 300 cookies. Once the limit of 300 is reached, the browser starts deleting the old cookies. A cookie can only hold up to 4KB of data.

Viewstate: When you store data in viewstate, that data is sent to the browser in an html hidden field and the data is stored in an encoded format that only the server (not the client) can decode. Among the client side state management, viewstate is relatively the most secure option. The hidden field in viewstate looks something like this.

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE4OTkzNDgzMDMPFgIeAmR0MqZFAAEAAAD/////AQAAAAAAAAAMRgAAAE5TeXN0ZW0uRGF0YSwgVmVyc5frbj0yLjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAABVTeXN0ZW0uRGF0YS5EYXRhVGFibGUDAAAAGURhdGFUYWJsZSQTW1VfP3zY1V" />

Note here that even is you disable viewstate, you would still see a hidden field as shown above. The reason is,   the asp.net engine saves the values of all the asp.net controls in viewstate. This feature cannot be disabled.

The viewstate is a very useful feature to save the state of usercontrols or other data that needs to be persisted between postbacks, without eating up the server resources. Viewstate can only be used for postbacks to the same page. ( If you want to retain information from one page to another, cookie or query strings are better options.)

An increased viewstate size means all that data is posted back and forth over the network (between the browser and the asp.net server) for every postback. This can in extreme cases, even add upto minutes to the time it takes to reload the page after a postback.

NOTE: To store the instance of a custom class in viewstate, mark the class with a [Serializableattribute.  

Query String: A  query string is passed through the url. For example if you make an invalid login attempt in facebook, you would see something like

The part ?login_attempt=1 is a query string.  Query strings are typically used to send data from one page to another or to retain data between postbacks to the same page. Most browsers impose a 2083 character limit on the query string so query strings can be used only for a small amount of data.

Hidden fields: Hidden fields control can be used to store data between postbacks to the same page. When you use an asp.net hidden field, then the html that is send to the browser is something like
<input type="hidden" value="myValue" />
There are two distinct advantages of hidden fields that I personally find appealing
1>You can set a serverside eventhandler that executes when the value of the hidden control changes between postbacks.
2>This value can be easily accesed by javascript.

Server side state management

The advantage of server side state management is that all that data is not sent across the network and the data stored is more secure. However, the downside is that more server resources utilized. Lets look at some of the server side state management options

Session: When you first visit an asp.net website, the asp.net web application assigns you a session ID that is stored in a cookie. You can also choose cookie less sessions by setting it in your web.config as shown.

<system.web>
      <sessionState mode="InProc" cookieless="true"  timeout="20"/>

</system.web>
When you choose cookieless session, then the session ID is stored in the url.

You can store data pertaining to sessions in session variables by doing something like
Session["userdetails"] = "xxx"; The default timeout for a session (and hence session variables) is 20 minutes. But this can be changed in the config file.

Certain points to note about sessions:
  • Session variables are stored in the RAM of the application server.
  • The asp.net session ID is stored in a cookie named "ASP.NET_SessionId". The assigned session ID looks something like hpb1lq55a0kdh3jdrtk4rhmruw.
  • The cookie that stores the session id is non persistent (which means when you close the the browser, this cookie is lost).
  • 20 minutes after the users last communication with the client, the session is terminated.
  • You can terminate the session on a button click (suppose log out button) by using Session.Abandon()
  • You can handle beginning and ending of sessions in Global.asax
  • Response.Redirect doesnot work in Global.asax
  • You get one sessionID at a time for a particular browser type. If you open the same web application in different browsers, say one in ie and another in firefox, then you get assigned two different session IDs in two different cookies (one in a firefox's cookie and another in  ie's cookie)
  • For cookieless sessions, even if you open the web site in multiple windows of the same browser, you get a new session ID for each window.

Application State: Application state is usually used to store small amounts of data that is global to the entire application. You generally don't use application variables for frequently changing data. Application variables are created by using something like 
Application["myValue"]="xxx"
Application variables are lost when an application is restarted.

Cache: Cache is similar to application state as in, it is available throughout the application. But it differs from application state in flexibility. There is a lot more you can do with cache, such as set a cache timeout, set a cache priority (when the application server is low on resources it starts getting rid of cache, starting from the low priority cache) etc.

Check this out for a continuation of discussion on caching
http://dotnetanalysis.blogspot.com/2011/08/caching-in-aspnet.html




Further Reading:

ASP.NET State Management Recommendations:
http://msdn.microsoft.com/en-us/library/z1hkazw7.aspx

Basic Security Practices for Web Applications:
http://msdn.microsoft.com/en-us/library/zdh19h94.aspx


2 comments:

Comments will appear once they have been approved by the moderator