title: C#, WCF : The remote server returned an error: (413) Request Entity Too Large
body: <p>Before marking as duplicate or down voting please first go through my scenario.
  I saw other developers running into the similar problem and tried to apply the solution. </p>
  
  <p><strong>Scenario:</strong> 
  The problem is my code is running fine in the development environment, passes staging but fails in the production. Out of the three different upload requests made to the three user machine of the same company 2/3 failed and one uploaded successfully. </p>
  
  <p>error printed in log file for the failing user:
    <strong>"OnUploadFileCompleted: UploadFileCompletedEventArgs has error: Message: The remote server returned an error: (413) Request Entity Too Large."</strong></p>
  
  <p>But the upload file was just <strong>1471834 bytes</strong> (1.4 MB approx).</p>
  
  <p><strong>Server Config:</strong> 
  I could see that people have been suggesting to set the <strong>maxReceivedMessageSize</strong> to maximum value which had been already set to 2GB. I tried to replicate the scenario by setting the maxReceivedMessageSize to 300KB than the upload folder size which was around 3MB, but didn't replicate the issue. </p>
  
  <p>Could it be due to some difference in development and production environment that is triggering the issue? </p>
  
  
  
  <pre><code>&lt;system.serviceModel&gt;
      &lt;diagnostics performanceCounters="All" /&gt;
      &lt;services&gt;
        &lt;service behaviorConfiguration="Psoft.Platform.PSPlatformServiceImplBehavior" name="PenSft.Platform.PSPlatformServiceImpl"&gt;
          &lt;endpoint address="net.tcp://localhost:8000/PSPlatform/service" binding="customBinding" bindingConfiguration="Custom_NetTcpBinding" name="clientService" contract="PenSft.Platform.IPSPlatformService" /&gt;
          &lt;endpoint address="net.tcp://localhost:8000/PSPlatform/register" binding="customBinding" bindingConfiguration="Custom_NetTcpBinding" name="clientRegister" contract="PenSft.Platform.IClientRegistrationService" /&gt;
          &lt;endpoint address="net.tcp://localhost:8001/PSPlatform/service" binding="customBinding" bindingConfiguration="Custom_NetTcpBinding" name="consoleService" contract="PenSft.Platform.IPSPlatformService" /&gt;
          &lt;endpoint address="http://localhost:8118/PSPlatform/service" binding="wsHttpBinding" bindingConfiguration="HttpBinding" name="httpClientService" contract="PenSft.Platform.IPSPlatformService" /&gt;
          &lt;host&gt;
            &lt;timeouts openTimeout="00:02:00" /&gt;
          &lt;/host&gt;
        &lt;/service&gt;
      &lt;/services&gt;
      &lt;bindings&gt;
        &lt;customBinding&gt;
          &lt;binding name="Custom_NetTcpBinding" closeTimeout="00:05:00" openTimeout="00:05:00" sendTimeout="00:05:00"&gt;
            &lt;transactionFlow transactionProtocol="OleTransactions" /&gt;
            &lt;security defaultAlgorithmSuite="Default" authenticationMode="SecureConversation" requireDerivedKeys="true" securityHeaderLayout="Strict" includeTimestamp="true" keyEntropyMode="CombinedEntropy" messageProtectionOrder="SignBeforeEncryptAndEncryptSignature" messageSecurityVersion="Default" requireSecurityContextCancellation="true" requireSignatureConfirmation="false"&gt;
              &lt;secureConversationBootstrap defaultAlgorithmSuite="Default" authenticationMode="MutualSslNegotiated" requireDerivedKeys="true" securityHeaderLayout="Strict" includeTimestamp="true" keyEntropyMode="CombinedEntropy" messageProtectionOrder="SignBeforeEncryptAndEncryptSignature" messageSecurityVersion="Default" requireSecurityContextCancellation="true" requireSignatureConfirmation="false"&gt;
                &lt;localClientSettings cacheCookies="true" detectReplays="true" replayCacheSize="900000" maxClockSkew="01:00:00" maxCookieCachingTime="Infinite" replayWindow="00:05:00" sessionKeyRenewalInterval="10:00:00" sessionKeyRolloverInterval="00:05:00" reconnectTransportOnFailure="true" timestampValidityDuration="00:05:00" cookieRenewalThresholdPercentage="60" /&gt;
                &lt;localServiceSettings detectReplays="true" issuedCookieLifetime="00:15:00" maxStatefulNegotiations="1000" replayCacheSize="900000" maxClockSkew="01:00:00" negotiationTimeout="00:01:00" replayWindow="00:05:00" inactivityTimeout="00:02:00" sessionKeyRenewalInterval="15:00:00" sessionKeyRolloverInterval="00:05:00" reconnectTransportOnFailure="true" maxPendingSessions="1000" maxCachedCookies="1000" timestampValidityDuration="00:05:00" /&gt;
              &lt;/secureConversationBootstrap&gt;
              &lt;localClientSettings cacheCookies="true" detectReplays="true" replayCacheSize="900000" maxClockSkew="01:00:00" maxCookieCachingTime="Infinite" replayWindow="00:05:00" sessionKeyRenewalInterval="10:00:00" sessionKeyRolloverInterval="00:05:00" reconnectTransportOnFailure="false" timestampValidityDuration="00:05:00" cookieRenewalThresholdPercentage="60" /&gt;
              &lt;localServiceSettings detectReplays="true" issuedCookieLifetime="10:00:00" maxStatefulNegotiations="1000" replayCacheSize="900000" maxClockSkew="01:00:00" negotiationTimeout="00:01:00" replayWindow="00:05:00" inactivityTimeout="00:02:00" sessionKeyRenewalInterval="15:00:00" sessionKeyRolloverInterval="00:05:00" reconnectTransportOnFailure="false" maxPendingSessions="1000" maxCachedCookies="1000" timestampValidityDuration="00:05:00" /&gt;
            &lt;/security&gt;
            &lt;binaryMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16" maxSessionSize="2048"&gt;
              &lt;readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /&gt;
            &lt;/binaryMessageEncoding&gt;
            &lt;tcpTransport manualAddressing="false" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" connectionBufferSize="16384" hostNameComparisonMode="StrongWildcard" channelInitializationTimeout="00:00:30" maxBufferSize="2147483647" maxPendingConnections="2000" maxOutputDelay="00:00:00.5000000" maxPendingAccepts="100" transferMode="Buffered" listenBacklog="300" portSharingEnabled="false" teredoEnabled="false"&gt;
              &lt;connectionPoolSettings groupName="default" leaseTimeout="00:05:00" idleTimeout="00:02:00" maxOutboundConnectionsPerEndpoint="2000" /&gt;
            &lt;/tcpTransport&gt;
          &lt;/binding&gt;
        &lt;/customBinding&gt;
        &lt;netTcpBinding&gt;
          &lt;binding name="TcpBinding" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"&gt;
            &lt;readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /&gt;
            &lt;security mode="Message"&gt;
              &lt;message clientCredentialType="Certificate" /&gt;
            &lt;/security&gt;
          &lt;/binding&gt;
        &lt;/netTcpBinding&gt;
        &lt;wsHttpBinding&gt;
          &lt;binding name="HttpBinding" closeTimeout="00:05:00"  openTimeout="00:05:00" sendTimeout="00:05:00" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"&gt;
            &lt;readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /&gt;
            &lt;security mode="Message"&gt;
              &lt;message clientCredentialType="None" /&gt;
            &lt;/security&gt;
          &lt;/binding&gt;
        &lt;/wsHttpBinding&gt;
      &lt;/bindings&gt;
      &lt;behaviors&gt;
        &lt;serviceBehaviors&gt;
          &lt;behavior name="PenSft.Platform.PSPlatformServiceImplBehavior"&gt;
            &lt;serviceMetadata httpGetEnabled="false" /&gt;
            &lt;serviceThrottling maxConcurrentCalls="6000" maxConcurrentSessions="6000" maxConcurrentInstances="6000" /&gt;
            &lt;serviceDebug includeExceptionDetailInFaults="true" /&gt;
            &lt;dataContractSerializer maxItemsInObjectGraph="2147483647" /&gt;
            &lt;serviceCredentials&gt;
              &lt;clientCertificate&gt;
                &lt;authentication certificateValidationMode="None" /&gt;
              &lt;/clientCertificate&gt;
              &lt;serviceCertificate findValue="PenSftServiceAuth" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" /&gt;
            &lt;/serviceCredentials&gt;
          &lt;/behavior&gt;
        &lt;/serviceBehaviors&gt;
      &lt;/behaviors&gt;
    &lt;/system.serviceModel&gt;
  </code></pre>
  
  
  
  <p><strong>Web.config:</strong></p>
  
  
  
  <pre><code>    &lt;system.webServer&gt;
      &lt;!-- security is added to control the allowed upload file size.
      source : http://stackoverflow.com/questions/24930058/file-upload-the-remote-server-returned-an-error-413-request-entity-too-large
      Warning : gives 404 not found error.
      --&gt;
      &lt;!--&lt;security&gt;
        &lt;requestFiltering&gt;
          &lt;requestLimits maxAllowedContentLength="30000" /&gt; --&gt;&lt;!--in bytes::30 KB --&gt;&lt;!--
        &lt;/requestFiltering&gt;
      &lt;/security&gt;--&gt;
      &lt;modules&gt;
        &lt;add name="PenSftServerHeaderModule" type="PenSftServerHeaderModule"/&gt;
      &lt;/modules&gt;
      &lt;handlers&gt;
        &lt;add name="MsiDownloadHandler" verb="*" path="*.msi" type="MsiDownloadHandler, ManagementConsoleV2, Version=1.0.0.0, Culture=neutral" resourceType="Unspecified" /&gt;
      &lt;/handlers&gt;    
      &lt;validation validateIntegratedModeConfiguration="false" /&gt;
    &lt;/system.webServer&gt;
  </code></pre>
  
  
  
  <p><strong>DesktopClient:</strong>
  Few code snippet has been placed. The condition insde event which prints out the particular log has been also placed. If you need more information please let me know. </p>
  
  <pre><code>//inside UploadLogs() funstion.
  using (var wc = new WebClient())
  {
      wc.UploadFileCompleted += OnUploadFileCompleted;
      wc.UploadFileAsync(address.Uri, null, strLogsFile, strLogsFile);
  
      ......
      ......
  }
  //end
  
  private static void OnUploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
  {
      .......
  
      if (e.Cancelled)
      {
          _uploadError = e.Error;
          Log.Trace(string.Format("OnUploadFileCompleted: UploadFileCompletedEventArgs Cancelled has error: Message: {0}", e.Error.Message));
      }
  
      ....
  
  }
  </code></pre>