Monday, March 26, 2012

Fixing "URL-encoded form data is not valid" Error in ASP.NET

Today I had to solve a tricky error raised on the back-end system implementation I'm currently leading. Whenever a user tried to submit the values of a heavy loaded ASP.NET MVC form, the system was throwing the following exception:

System.Web.HttpException (0x80004005): The URL-encoded form data is not valid. ---> System.InvalidOperationException: Operation is not valid due to the current state of the object.
at System.Web.HttpValueCollection.FillFromEncodedBytes(Byte[] bytes, Encoding encoding)

The error is thrown immediately after clicking the submit button, and although I have logging implementation in the code, nothing was being reported on the app logs.

I then manage to copy the data to my local development environment and was able to replicate the issue. I did a few tests double checking if it was a JavaScript issue or something around the front-end part, but I could quickly discard it.

After researching on-line around forums, dev sites and official documentation I found out that in ASP.NET there is a security default setting that restricts form key/value fields to a maximum of 1000. Although it is probably more than enough for most cases, in this particular scenario I needed to be able to manage many more keys. Luckily the fix didn't require much effort. It is enough to add a new configuration settings on the "" section of your application configuration file to tell ASP.NET secutity settings to allow a bigger number of form key/value fields.

That will increase the default ASP.NET Security Form Key collection to 2000 instead of the default 1000 value. After updating the configuration file I was able to solve the issue right away.

Keep this in mind or on a handy place, since dealing with those kind of errors are tricky and difficult to solve because the lack of error information.

Hope it helps !