State Management in ASP.NET

In today’s post, we’ll explore the various state management techniques ASP.NET provides. But first we need to underline the fact several times that HTTP is a stateless protocol. Being so, it provides huge scalability, but the programmers need to find some ways to store data (even forms) between page requests.

ASP.NET has several answers to this question:

  1. View State
  2. Query String
  3. Custom Cookies
  4. Session State
  5. Application State
  6. Control State
  7. Profiles
  8. Caching

Now I’d like to examine the first six, because I plan to give the topic of caching a full post, and profiles are a bit different from the others.

View State
View State is used mostly by controls to store their appearance and some other information about them. It stores data in a dictionary (the key is a string, and the data type can be any serializable .NET class), within the bounds of a single page. Data being stored in a hidden field, encoded into a Base64 string by default.

Decoding Base64 strings is an easy task, so you should never include sensitive data in the View State. View State can be turned off (in the application, page or control level). This is in some occasions necessary, because when you use View State massively, it can grow enormous. And this enormous amount of text is posted back to the server, then returned to the client in every postback. This won’t affect server memory, but the transaction times of pages will be quite lengthy.

Enough of introduction, let’s see View State in action:

ViewState[“MyVar”] = “Hello ViewState!”;
string MyVar = string.Empty;
if(ViewState[“MyVar”] != null)
{
MyVar = ViewState[“MyVar”].ToString();
}

Naturally the first line of code enters a new entry to the View State dictionary called MyVar. The other lines try to retrieve this value. First you should always check for whether the key exists or not, and only try to retrieve it when it does.

I think the way to use View State doesn’t require further explanation. Let’s dig us deeper into the security of View State.

By default, View State data is encoded as Base64 string. However, you are able to encrypt View State data, in the application or in the page level. You just need to set the ViewStateEncryptionMode property. This has three possible values:

  • Always: always encrypts View State data (using the machine-specific hash-code). Adds performance overhead.
  • Never: never encrypts View State data.
  • Auto: the default. Only encrypts View State data, when a page calls the RegisterRequiresViewStateEncryption method.

When working with a web farm, you can have interesting errors regarding to View State. This is because when the server retrieves View State from the client, it checks its validity with the machine key. By default, machine keys are different for all servers in a given web farm. So two solutions exist: the strongly advised: set the machine key to the same value on all servers, and the strongly discouraged: set the EnableViewStateMac property to false.

Query String

Query String helps you pass a limited amount of text data from one page to another. It provides the least security of all the state management techniques, because it’s the most tempting for the user to modify. You can access Query String data from the Request.QueryString dictionary.

Custom Cookies

Cookies are small files created on the client (or stored in its memory). Cookies are typically used to store web site preferences, such as color schema, etc. Another common usage of cookies is as a security token.

Cookies are easy to tamper with, can be disabled by the user, etc. To read the cookies of the user, you’d use the Request.Cookies collection, to send a cookie, you add it through the Response.Cookies collection. There is no way to delete a cookie, the easiest way is to set its expiration date to a date that is passed.

Session State

There is already a post about session state in this series, you’ll find it at Configuring Session State.

A quick review: Session State is unique to every user, can be stored in a bunch of locations (most common is the memory of the server). It is never returned to the client, so it’s the safest of the state management techniques. It’s essentially a dictionary, the key is a string, the value can be any serializable .NET types.

Application State

Application State is very similar to Session State. The main difference is that it’s global, so it’s shared by all the users of the site. To modify the values stored in Application State, it’s generally a good idea to lock it, like this:

Application.Lock();
int views = 0;
If(Application[“Views”] != null)
views= (int)Application[“Views”];
views++;
Application[“Views”] = views;
Application.UnLock();

Control State

Control State is a fallback state management technique for controls with disabled View State. You can use both techniques for the same control, the main difference is that values stored in the Control State can never be disabled.

To use Control State, you should build it into a custom control. There are three steps:

  1. Register that the control needs access to the Control State in the OnInit method.
  2. Override the SaveControlState method (object) to save data.
  3. Override the LoadControlState method (void) to load data.

An example:

protected override void OnInit(EventArgs e)
{
page.RegisterRequiresControlState(this);
base.OnInit(e);
}
protected override object SaveControlState()
{
return myVar != string.Empty ? (object) myVar : null;
}
protected override void LoadControlState(object state)
{
if(state!=null)
myVar =(string)state;
}

Further Readings

State Management
View State
Control State
Session
Cookies

Advertisements

Tags: , , ,

%d bloggers like this: