Search code examples
c#.netwcf-web-api

C# WCF Web Api 4 MaxReceivedMessageSize


I am using the WCF Web Api 4.0 framework and am running into the maxReceivedMessageSize has exceeded 65,000 error.

I've updated my webconfig to look like this but because I am uisng the WCF Web Api I think this isn't even used anymore as I am no longer using a webHttpEndpoint?

<standardEndpoints>
      <webHttpEndpoint>
        <!-- 
            Configure the WCF REST service base address via the global.asax.cs file and the default endpoint 
            via the attributes on the <standardEndpoint> element below
        -->
        <standardEndpoint name="" 
                          helpEnabled="true" 
                          automaticFormatSelectionEnabled="true"
                          maxReceivedMessageSize="4194304" />       

      </webHttpEndpoint>

Where do I specify MaxReceivedMessageSize in the new WCF Web Api?

I've also tried a CustomHttpOperationHandlerFactory to no avail:

  public class CustomHttpOperationHandlerFactory: HttpOperationHandlerFactory
    {       
        protected override System.Collections.ObjectModel.Collection<HttpOperationHandler> OnCreateRequestHandlers(System.ServiceModel.Description.ServiceEndpoint endpoint, HttpOperationDescription operation)
        {
            var binding = (HttpBinding)endpoint.Binding;
            binding.MaxReceivedMessageSize = Int32.MaxValue;

            return base.OnCreateRequestHandlers(endpoint, operation);
        }
    }

Solution

  • If you're trying to do this programatically (via using MapServiceRoute with HttpHostConfiguration.Create) the way you do it is like this:

    IHttpHostConfigurationBuilder httpHostConfiguration = HttpHostConfiguration.Create(); //And add on whatever configuration details you would normally have
    
    RouteTable.Routes.MapServiceRoute<MyService, NoMessageSizeLimitHostConfig>(serviceUri, httpHostConfiguration);  
    

    The NoMessageSizeLimitHostConfig is an extension of HttpConfigurableServiceHostFactory that looks something like:

    public class NoMessageSizeLimitHostConfig : HttpConfigurableServiceHostFactory
    {
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            var host = base.CreateServiceHost(serviceType, baseAddresses);  
    
            foreach (var endpoint in host.Description.Endpoints)
            {
                var binding = endpoint.Binding as HttpBinding;    
    
                if (binding != null)
                {
                    binding.MaxReceivedMessageSize = Int32.MaxValue;
                    binding.MaxBufferPoolSize = Int32.MaxValue;
                    binding.MaxBufferSize = Int32.MaxValue;
                    binding.TransferMode = TransferMode.Streamed;
                }
            }
            return host;
        }
    }