Friday, April 20, 2012

ASP.NET WebForm System.InvalidOperationException on postback: Operation is not valid due to the current state of the object.

If on a post-back in a WebForm of an ASP.NET application you get this error:
System.InvalidOperationException: Operation is not valid due to the current state of the object.
And the stack trace is:
in System.Web.HttpRequest.FillInFormCollection()
in System.Web.HttpRequest.get_Form()
in System.Web.HttpRequest.get_HasForm()
in System.Web.UI.Page.GetCollectionBasedOnMethod(Boolean dontReturnNull)
in System.Web.UI.Page.DeterminePostBackMode()
in System.Web.UI.Page.ProcessRequestMain(
                           Boolean includeStagesBeforeAsyncPoint,
                           Boolean includeStagesAfterAsyncPoint)

You are trying to send a lot of values (TextBox, CheckBox, etc..) to the server.

The solution are two:
  1. refactor your page (not always easily possible);
  2. change the security settings;
Why security settings? Because the exception is caused by an internal security check done by the framework on the number of the posted values.
So you have to increase that limit on your web.config file, adding this key:

<appSettings>
    <add key="aspnet:MaxHttpCollectionKeys" value="2000" />
</appSettings>

Of course change this values at your needs.

 If your Exception occur when your send JSON with JavaScript, you have to add this other key to the web.config file:

<appSettings>
    <add key="aspnet:MaxHttpCollectionKeys" value="2000" />
</appSettings>

Again, change this value at your needs.

Happy exception handling! ;-)

No comments:

Post a Comment