Tuesday, 17 December 2013

Increasing the maximum received message size for WCF with SharePoint 2013

Today I was tasked with an issue of fixing a file upload problem. The server was returning a 413 "Request Entity Too Large" message. The file I was trying to upload was around 3MB, but the server refused anything this big. A few problems arose that are worth noting in fixing this issue.

A bit of Googling brought up the following result: http://msdn.microsoft.com/en-us/library/ff599489.aspx

Which in theory works. However it's not as straightforward as the article implies, as a few things were missed:
  • Run the code as farm administrator
  • Ensure the service name is lower case (this one caught me out..)
  • Clearing up

Run the code as farm administrator

Simply using the code in the MSDN article won't work if you try in your WCF service, you'll get an Access Denied error on SPWebService.Update(). The way I got round this was creating an event receiver on my project Feature that was scoped at the farm level, this allowed me to override FeatureActivated and FeatureDeactivating and run the code with the right permissions.

Ensure the key for the service name is lower case

There is no mention of this in the MSDN article, but it's very important as otherwise the changes won't take effect. I noticed that all the other keys in SPWebService.ContentService.WcfServiceSettings were lowercase, and it turns out mine has to be too. This should be the same name of your *.svc file under ISAPI.

Clearing up

Nothing is mentioned about clearing up either, but it needs doing and this caught me out too. Make sure you override the FeatureDeactivating and remove your settings from SPWebService.ContentService.WcfServiceSettings otherwise you will get strange behaviour (like the settings persisting). Also make sure you set the SPWebService.ContentService.MaxReceivedMessageSize back to 0 (the default setting).

The Code

   public class MyApiEventReceiver : SPFeatureReceiver  
     public override void FeatureActivated(SPFeatureReceiverProperties properties)  
       SPWebService contentService = SPWebService.ContentService;  
       contentService.ClientRequestServiceSettings.MaxReceivedMessageSize = -1;  
       SPWcfServiceSettings wcfSettings = new SPWcfServiceSettings();  
       wcfSettings.MaxReceivedMessageSize = (1024 * 1024) * 15;  
       contentService.WcfServiceSettings["wizard.svc"] = wcfSettings;  
     public override void FeatureDeactivating(SPFeatureReceiverProperties properties)  
       SPWebService contentService = SPWebService.ContentService;  
       contentService.ClientRequestServiceSettings.MaxReceivedMessageSize = 0;