title: Deadlock reading async response content from async DelegatingHandler in webapi
body: <p><strong>Problem</strong></p>
  
  <p>I'm using a DelegatingHandler in WebAPI to read the response Content and audit it to the database.</p>
  
  <p>When the code gets to .ReadAsStringAsync() it appears to lock and prevent other requests from completing. I only know this, because when I remove the offending line, it works perfectly.</p>
  
  <pre><code>public static void Register(HttpConfiguration config)
  {
      config.MessageHandlers.Add(new ResourceAuditHandler());
  }
  
  public class ResourceAuditHandler : DelegatingHandler
  {
      protected override async Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request,
                                                             CancellationToken cancellationToken)
      {
          var response = await base.SendAsync(request, cancellationToken);
  
          string content = "";
          if (response.Content != null)
          {
              //THIS SEEMS TO CREATE DEADLOCK!
              content = await response.Content.ReadAsStringAsync(); 
          }
  
          AuditResponseToDatabase(content);
  
          return response;
      }
  }
  </code></pre>
  
  <p><strong>Possible cause</strong></p>
  
  <p>I've read this can happen when two bits of the application are trying to read the content from same request/response (a DelegatingHandler and Controller/ModelBinder)... Or more specifically when one tries to read the <strong>.Result</strong> of the async response, but the other instance has already read the Result / Response Stream, which is then null.</p>
  
  <p>My first request, hits a simple controller, but the second request, hits a controller with an attribute that checks the Action parameter "id" to check its not null. I've read that, when both a DelegatingHandler and the controller ModelBinder are trying to read from the Response you get deadlock.</p>
  
  <p><strong>Alternative method</strong> (which also fails)</p>
  
  <p>I've also tried using the other approach (as seen in other SO questions) which uses <strong>.ReadAsByteArrayAsync()</strong> but this still seems to lock. I understood that this method doesn't use the <strong>.Result</strong> approach and reads it directly from the response stream (somehow).</p>
  
  <pre><code> var response = await base.SendAsync(request, cancellationToken);
  
   string content= "";
   if (response.Content != null)
   {
       var bytes = await response.Content.ReadAsByteArrayAsync();
       responseContent = Encoding.UTF8.GetString(bytes);
   }
  
   AuditResponseToDatabase(content);
  </code></pre>
  
  <p>Please help!</p>