Wednesday 15 June 2011

WCF: How to increase request size limit

When you generate a new WCF web service using Visual Studio it will use "wsHttpBinding" with its default configuration. Default endpoint configuration generated for a new web service looks like that:
<endpoint
address=""
binding="wsHttpBinding"
contract="Your.Namespace.IService1" />

This will work well in most cases at development stage. However, before deploying the web service you should consider changing the default settings according to your needs (e.g. change security settings).

The problem you may often get already at development stage is the following error thrown when you send large amount of data to your service (e.g. a large file):

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

The request fails because it's size exceeds the limit allowed by your service. The default request size limit is 65536 bytes (i.e. 64KB). In order to change this limit you need to use custom binding configuration. The following example sets the request size limit to 50MB (i.e. 52428800 bytes) using custom binding configuration:
<endpoint
address=""
binding="wsHttpBinding"
bindingConfiguration="myCustomConf"
contract="Your.Namespace.IService1" />
<bindings>
<wsHttpBinding>
<binding name="myCustomConf"
maxReceivedMessageSize="52428800"
maxBufferPoolSize="52428800" >

(...)
</binding>
</wsHttpBinding>
</bindings>

In example above I used custom binding configuration named 'myCustomConf'. You can read more about wsHttpBinding properties here.

The code above cares about configuration of your WCF service. However, you'll most likely need to increase the request size limit for Asp.NET runtime as well:
<system.web>
<httpRuntime maxRequestLength="51200" />
(...)
</system.web>

Note that Asp.Net maximal request size is set in KB whereas WCF configuration uses bytes! So, in order to allow requests of size 50MB you'll need to set value of 51200KB.

No comments: