title: How to stop IIS returning 502.3 - Bad Gateway when ASP.Net Core returns 413 (Request body too large)?
body: <p>I have a ASP.Net core site. </p>
  
  <p>I have set a custom max request size.</p>
  
  <p>Either:</p>
  
  <pre><code> app.Use(async (context, next) =&gt;
       {
           int limit = 1024;
           context.Features.Get&lt;IHttpMaxRequestBodySizeFeature&gt;().MaxRequestBodySize = limit;
           await next.Invoke();
       });
  </code></pre>
  
  <p>Or using the attribute <code>[RequestSizeLimit(1024)]</code></p>
  
  <p>When I host the site as a standalone console app it works correctly; returning <code>413</code> when I <code>POST</code> a payload larger than 1k (<em>in this example</em>).</p>
  
  <p>However when I deploy to be hosted on IIS or run from within IIS express I get:</p>
  
  <blockquote>
    <p>HTTP Error 502.3 - Bad Gateway </p>
  </blockquote>
  
  <hr/>
  
  <p>Here is an example controller which triggers the problem:</p>
  
  <pre><code>[Route("api/values")]
  public class ValuesController : Controller
  {
      // POST api/values
      [HttpPost]
      [RequestSizeLimit(1024)]
      public IActionResult Post()
      {
          string echo= "";
          try
          {
              using (StreamReader sr= new StreamReader(Request.Body))
              {
                  echo = sr.ReadToEnd();
              }
          }
          catch (Exception ex)
          {
              return StatusCode(413);
          }
          return StatusCode(200, echo);
      }
  }
  </code></pre>
  
  <p><em>I don't know if reading from the Body stream makes a difference. But because of reasons, I need to save the body verbatim to the Db. So it's a problem either way</em></p>
  
  <p>I have tried:</p>
  
  <ol>
  <li>Catching the exception and swallowing it in the controller</li>
  <li>Catching the exception and re-throwing it in the controller</li>
  <li>Catching the exception and swallowing it in the middleware pipeline</li>
  </ol>
  
  <p>They all have then same problem.</p>
  
  <p>Not setting a <code>RequestSizeLimit</code> and returning <code>413</code> works correctly through IIS though.</p>
  
  <p>So I think it is something to do with how Kestral passes back a response when it threw an exception internally...</p>
  
  <p><strong>What is going on exactly?</strong></p>
  
  <p><strong>How do I get IIS/Kestral to play nice?</strong></p>