Specifying Reader Quotas for WCF Services in SharePoint 2010

Creating custom WCF services for SharePoint 2010 is very easy. If you read the article here, Creating a Custom WCF Service in SharePoint Foundation, you’ll see how easy. Most of the article deals with the sample service, but only two steps deal with the actual service hosting. All you need to do for most scenarios is deploy an .svc file to the ISAPI folder in the SharePoint root and use the MultipleBaseAddressBasicHttpBindingServiceHostFactory class as your service host factory like so:

<%@ServiceHost
language="c#"


Factory="Microsoft.SharePoint.Client.Services.MultipleBaseAddressBasicHttpBindingServiceHostFactory,
Microsoft.SharePoint.Client.ServerRuntime, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"


Service="MyAssembly.MyService, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=2f6e123a83b3b3e5"

%>

 

That’s it! MultipleBaseAddressBasicHttpBindingServiceHostFactory does all the work required to set up the end points and bindings. You don’t need to do create a web.config file or write any WCF service code.

But, you might see some errors when you use the service like:

The maximum string content length quota (8192) has been exceeded while reading XML data. This quota may be increased by changing the MaxStringContentLength property on the XmlDictionaryReaderQuotas object used when creating the XML reader.

–OR–
The remote server returned an unexpected response: (400) Bad Request.

 

Both of these errors are caused by the message size. The first happens when a single parameter exceeds the default length of 8k and the second happens when the overall message size exceeds the default of 65k.

You can change these limits as follows:

//This code makes it possible to pass large messages (up to 10MB)
//To the outward facing service (not the service app)
//i.e. ISAPIMySolutionMyService.svc
//Note:10MB is not the upper limit, it's just what I'm using in this example


private void ConfigureWebService()
{
SPWebService contentService = SPWebService.ContentService;

SPWcfServiceSettings wcfServiceSettings = new SPWcfServiceSettings();
wcfServiceSettings.ReaderQuotasMaxStringContentLength = 10485760;
wcfServiceSettings.ReaderQuotasMaxArrayLength = 2097152;
wcfServiceSettings.ReaderQuotasMaxBytesPerRead = 10485760;
wcfServiceSettings.MaxReceivedMessageSize = 10485760;
contentService.WcfServiceSettings["MyService.svc"] = wcfServiceSettings;

contentService.Update();
}

Author: Doug Ware