Thursday, April 05, 2012

ThrowIfMaxHttpCollectionKeysExceeded Error When Populating WebPart

A custom WebPart won't show in the available WebPart list when it's deployed to WebPart Gallery by a Feature. In order to use such WebPart, we need to manually populate it inside SharePoint WebPart Gallery. What you do is go to site collection's WebPart gallery, click "New" button on the toolbar, select the WebPart and click "Populate Gallery" button:



It used to be working fine but all in a sudden I got an error when populating a WebPart:



This runtime error doesn't provide any hints. There're two options to see the error detail.

1. Go to SharePoint ULS logs in SharePoint_12_Or_14_Hive\LOGS and do the search.
2. Set <customErrors mode="Off" /> in SharePoint_12_Or_14_Hive\TEMPLATE\LAYOUTS\Web.config (not the WebApplication itself).

The error found in the ULS log is:

w3wp.exe (0x21BC) 0x1EB0 SharePoint Foundation Runtime tkau Unexpected System.InvalidOperationException: Operation is not valid due to the current state of the object. at System.Web.HttpValueCollection.ThrowIfMaxHttpCollectionKeysExceeded() at System.Web.HttpValueCollection.FillFromEncodedBytes(Byte[] bytes, Encoding encoding) at System.Web.HttpRequest.FillInFormCollection() d5fef840-8ad4-46a3-ab11-0b37346e7a9f

It turns out the submit form has too many post values. Adding following appSetting to the WebApplication's web.config (C:\inetpub\wwwroot\wss\VirtualDirectories\{WebApplication}\Web.config) resolves the problem:
 <appSettings>
     <add key="aspnet:MaxHttpCollectionKeys" value="2000" />
 </appSettings>
As the key name suggested it's an ASP.NET related setting. Why the error happens in SharePoint suddenly? We have installed some Microsoft and SharePoint security patches recently. The default maximum 500 post values policy was introduced by those patches, specifically from Critical MS11-100 patches.