Introduction

Recently, I developed a huge ASP.NET page, with more than 30 controls. As we all know, it's a good idea to disable the ViewState for the controls that don't actually need it, say Literals or Labels. After doing that, I noticed that the hidden ViewState field was still a few KBs big. This is obviously a big problem for the users that still don't have a broadband connection, because uploading 40 KB to the server is really a bad issue, especially when they begin to click the "Submit" button again and again because they don't notice any response. So, after a few searches through the Internet, I built a simple solution to compress the ViewState and therefore save a rough 50% of the bandwidth. This post by Scott Hanselman has been particularly useful. Although it's possible to use external libraries to perform compression tasks, I think the better solution is to use the GZipStream or DeflateStream that the .NET Framework 2.0 includes.

Compressing and Decompressing Data in Memory

First of all, we need a way to compress and decompress an array of bytes in memory. I put together this simple static class that exposes two methods: Compress and Decompress. The two available classes, GZipStream and DeflateStream, according to MSDN, use the same algorithm, so it's irrelevant which one you choose.

The code below is really simple, and doesn't need further explanation:

You need to save this class in a .cs file and put it in the App_Code directory of your ASP.NET application, making sure it's contained in the proper custom namespace (if you don't specify any namespace, the class will be available in the built-in ASP namespace).

Compressing the ViewState

Now, we can actually compress the ViewState of the page. To do that, we have to override the two methods LoadPageStateFromPersistenceMedium and SavePageStateToPersistenceMedium. The code simply uses an additional hidden field, __VSTATE, to store the compressed ViewState. As you can see, by viewing the HTML of the page, the __VIEWSTATE field is empty, while our __VSTATE field contains the compressed ViewState, encoded in Base64. Let's see the code.

In the first method, we just decode from Base64, decompress and deserialize the content of the __VSTATE, and return it to the runtime. In the second method, we perform the opposite operation: serialize, compress, and encode in Base64. The Base64 string is then saved into the __VSTATE hidden field. The LosFormatter object performs the serialization and deserialization tasks.

You may also want to create a new class, for example, CompressedPage, inheriting from System.Web.UI.Page, in which you override the two methods and then inherit your page from that class, for example MyPage : CompressedPage. Just remember that .NET has only single inheritance, and by following this way, you "spend" your only inheritance chance to use the ViewState compression. On the other hand, overriding the two methods in every class is a waste of time, so you have to choose the way that best fits your needs.

Performances and Conclusions

After a few tests, I noticed that the ViewState has been reduced from 38 KB to 17 KB, saving 44%. Supposing you have an average of 1 postback per minute per user, you could save more than 885 MB of bandwidth per month on every single user. That's an excellent result: you save bandwidth (and therefore money), and the user notices a shorter server response time.

I wanted to point out that this solution has a performance hit on the server's hardware. Compressing, decompressing, encoding, and decoding data is quite a heavy work for the server, so you have to balance the number of users with your CPU power and RAM.

why not just use server side viewstate? You save all the bandwith... and likelyt the cost of storing the state somewhere is less then compressing, sending, recieving and decompressing.... maybe when i have time(not likley) ill run some performance tests.
If you are using 2.0, server side viewstate is super easy, in 1.1, it's slightly more involved, but still easy enough.

Yes, you can store the ViewState on the server, using the Session object, but I don't believe that's a good solution when you have many users.
In my case I needed to compress the ViewState only in one page, so it's not a problem to compress and decompress it.

why use session? you can use DB, text file, whatever you want... jsut write an adapter for it.
It works well for many users
Agreed, the nice thing about your solution is the per page option, with 2.0 page adapters you have it for the app or not. What we do where I code most the time, is most pages/sections of the site are their own apps/virtual direcotries anyway.
In any case, I like the article, code, and idea.

I don't think so. A DB is surely slower than in-memory compression, and using files is even worse because you would have to set a file for every user... I think using Session it's the only way other than compression.
Moreover, using a DB or files introduces the new problem of managing expiration; on the other hand using Session would waste memory when the user goes away and the session expires after (default) 20 mins. If you have manhy "occasional" users you end up having hundreds open sessions but only a few of them are still used, wasting lots of memory.

My idea being that the method would be quite beneficial when mixed with using for example a server control that has some ajax uses. Think paging grid or something, where the return string itself could be rather large.
So, passing the compressed string to the client to be handled, with no .net framework, and just a browser, will he be able to decompress the data and use it?

I don't know, but I think that GZip works at bit-level so it would be impossible or highly difficult to decompress a GZip stream using JavaScript.
You may implement a simple compression algorithm and then decompress the data through JavaScript. You may consider RLE, but it doens't have high compression rates at all.

If you have big responses you should consider HTTP compression. I have written an article about it: Link. It uses GZipStream and it's really simple to implement.

I dont think its possible with javasdcript, anyway, i liked the idea of a page by page option so i made this property in my base page.
private bool _CompressViewState = false;
public bool CompressViewState
{
get
{
return _CompressViewState;
}
set
{
_CompressViewState = value;
}
}
There is also a global key to turn it on and off globaly, if we see performance is quick enough with it. we will have to test becuase our site has a failry large number of simultaneous users for most the day, so the cost of compression decompression on the server for everything may be to costly, but if our devs are careful and pick the right places, this could save quite a bit.

We were using Session objects to store state (using StateServer), but we found a problem with this. If the user has a session open in a browser and then presses Ctrl-N to open another browser window, BOTH IE browser windows were using the SAME session object on the server. This is because the session ID for the second IE window comes from the first window when you press Ctrl-N.

As you can imagine, having two browser windows using the same session state on the server is a recipe for disaster! We had to switch back to using the View State, and this article has been very useful in improving our application performance!

Yes it is! And the worst thing of all is that we didn't notice this until one of our customers found it.

By the way, our session state was a massive 168KB before compression! So the compression really helps here.

One of the other reasons we could not use in-process Session State on the server is because of server farms. You need to store the state in a central location, ruling out this mechanism of storing state also.

Not sure how this helps, as unique session IDs are sent to/from the client anyway.

Unless of course that you get a new Page object when the user presses Ctrl-N? If this is the case, then I think your solution would work. Is this what happens? (sorry, am in the middle of something else at the moment, and can't try it).

If the page is local cached when you "open new", both pages start from the same viewstate.

If it refereshed, the new page would get a "new" viewstate.

More importantly, by using a new guid on each page request, you don't end up assuming that the "current" viewstate belongs to an different page. Or that a "new" viewstate belongs to an old page (like hitting the back button a few times to get back to an old search)

I wonder what it will do with the available processor power on the server.

I think it's not a big problem. It seems that sending X KB of data takes more time than compressing them (I have read lots of articles about HTTP/text compression and similar topics).
I can tell that the page loads really faster than before, though.

If you need to run this solution on .NET 1.1, you only have to write different compression methods, for example using #ZipLib[^]: it's a ZIP library written in C#, supports .NET 1.1 and 2.0 and it's free and opensource. I never used it, though, so I cannot help you on this.
You could try the Scott Hanselman's post that I mentioned at the beginning of the article: he uses #ZipLib on .NET 1.1 and VB.NET.

Nicely written article, but for solving this problem you should investigate http compression. All newer browsers support this, and IIS6 includes it (but its off by default). This will compress your entire page, not just the viewstate. I've frequently seen 70-80% compression on pages. Google httpzip for more information. It won't compress the upload upon a submit, though, but in general I think its preferable this solution.

I'm investigating HTTP compression too, but what I wanted in the first instance was a small ViewState because even on my DSL line the postback was really slow.
HTTP compression is nice, but needs that the client as well as the server supports it.
Anyway, I'm searching a way to enable HTTP compression on aspx pages via code, so it can also be enabled or disabled when needed without touching IIS (on most shared hosting plans you haven't access to IIS, for instance).

Yes, its all about trade-offs. I don't know the details of your app, but there have been several articles about storing viewstate on the server, either in session state or sql server. On a hosted server session state may be your only choice. Not sending the viewstate at all is the best compression! But it has its drawbacks too.

I didn't say that.
I said that you can use #ZipLib to do the same in .NET 1.1, but I never tried that. I never tried to use #ZipLib at all.
The post I mentioned at the beginning of the article uses #ZipLib, so you may find it useful.

The concern I have with this approach is that the viewstate will not be compressed until after it is base-64 encoded. I don't have any specific evidence but I suspect that the viewstate is much more compressible before being encoded, as is suggested in this article, so using HTTP compression would not provide as much compression.

Hey, I'm liking the concept but you didnt tell what all changes we require to do on page, e.g. __VIEWSTATE will still be used or not? I understand that we need to inherit all code behinds from the class you created instead of System.Web.UI.Page but what else changes do we need to do or will just inheriting sufficize compression need?

As I say in the article, __VIEWSTATE will be in the page, but it will be always empty. Instead, the new __VSTATE will contains the compressed data.

To enable compression, just include in the project the Compression class, and override the two methods described in the article in the pages in which you want to compress the ViewState.

You can also create a new class (say CompressedPage : System.Web.UI.Page) inheriting, in which override the two methods and then using it as a base class for your pages instead of the usual Page class (MyPage : CompressedPage).

I didn't apply the second way because in my project I already had to inherit MyPage from another class, and as you know .NET has only simple inheritance and because I had to enable or disable compression following the configuration options.

Anyway, thanks for your feedback. I'll update the article, specifying the two different ways to enable compression.