View State Issues in ASP.Net

We are getting some of the view state related errors in our application.
  • Invalid view state.
  • Unable to read beyond the end of the stream.
  • The serialized data is invalid.
  • The client disconnected.
The reason for this errors are one of the one mentioned below:

1. The application may be deployed across farms and the encryption/Decryption keys may vary in the servers, so it may throw errors intermittently.
2. The View state may be very large or bloated, so it may reduce the application performance and may cause issue while serialization or deserialization of View state.

Possible solution for this issue are,

1. We can set the encryption validation key at the application level in the web.config file. It looks like the one mentioned below.

<machinekey decryption="AES" decryptionkey="4C05D6B56FA0A057F519884A1C3B5B42B14491ED56CB44F942EE3A0CA2848D29" validation="SHA1" validationkey="ABFD56FE84823AE69E9A613CE998803F4246FE0D96DC48E7BB9E715B0A57352CEFB35264EFB8C0F710E154F42B7460B7CDE9A99F225DA796DEE5E5F94F8F7188"></machinekey>

We can generate keys online from this location.

<pages enableviewstatemac="true">

We can also set the enableViewStateMac to true, but we have some issues when we implement the both these fixes. It may throw user a run time error or compiler warning. It will not allow you to debug sometimes.

3. Other simple solution to overcome this issue is to break the view state in to multiple chunks so that we can avoid the serialization error. This can be achieved by setting a simple property in the pages element of config file.

<pages maxpagestatefieldlength="20">

4. We can also compress and decompress the view state using a simple logic and have that code in the Base Page of the application. We can use compression at the page level by setting a property. Please check the code project link for a detailed explanation on this.

These are some of the things I found during my search, i put all the points in one stop for your reference. It worked for me. Hope the same for you all.

1 comment: