title: Why can't I catch exception from HttpClient SendAsync when using ObjectContent
body: <p>I can't seem to catch certain exceptions thrown from the System.Net.Http.HttpClient's SendAsync method. Specifically, the ProtocolViolationException, thrown from the HttpWebRequest.ChechProtocol method. The code seems to deadlock or hang, and the catch is never entered.</p>
  
  <p>I've created an NUnit unit test to illustrate the issue clearly.</p>
  
  <pre><code>public class TestClass
  {
      public bool TestProperty { get; set; }
  }
  
  [Test]
  public async Task CanCatchExceptionFromHttpClientSendAsync()
  {
      var caughtException = false;
  
      try
      {
          var request = new HttpRequestMessage(HttpMethod.Get, "http://somedomain.com")
          {
              Content = new ObjectContent&lt;TestClass&gt;(
                  new TestClass { TestProperty = true },
                  new JsonMediaTypeFormatter())
          };
  
          await new HttpClient().SendAsync(request);
      }
      catch (Exception)
      {
          caughtException = true;
      }
  
      Assert.IsTrue(caughtException);
  }
  </code></pre>
  
  <p>using StringContent instead of ObjectContent the test passes. Am I missing something simple?</p>
  
  <p><strong>Update</strong></p>
  
  <p>Based on the fact that StringContent allows the exception to be caught, and ObjectContent deadlocks, I've been able to deduce that this is somehow related to the MediaTypeFormatter's WriteToStreamAsync method.</p>
  
  <p>I've managed to work around the problem by "pre-formatting" the content in to a ByteArrayContent like so:</p>
  
  <pre><code>private static async Task&lt;HttpContent&gt; CreateContent&lt;T&gt;(
      T value,
      string mediaType, 
      MediaTypeFormatter formatter)
  {
      var type = typeof(T);
      var header = new MediaTypeHeaderValue(mediaType);
  
      HttpContent content;
      using (var stream = new MemoryStream())
      {
          await formatter.WriteToStreamAsync(type, value, stream, null, null);
  
          content = new ByteArrayContent(stream.ToArray());
      }
  
      formatter.SetDefaultContentHeaders(type, content.Headers, header);
  
      return content;
  }
  </code></pre>
  
  <p>and then consuming it like this:</p>
  
  <pre><code>var content = await CreateContent(
      new TestClass(), 
      "application/json", 
      new JsonMediaTypeFormatter());
  
  var request = new HttpRequestMessage(HttpMethod.Get, "http://foo.com")
  {
      Content = content
  };
  </code></pre>
  
  <p>That at least allows the catch to work properly, but I</p>