3

I'm writing a unit test method that exercises code that, under the conditions of my test, is expected to throw an HttpResponseException with a specific response message.

The relevant portion of my test method code looks like this:

try
{
    MyClassBeingTested.MyWebServiceMethodBeingTested(myParameters);
}
catch (HttpResponseException ex)
{
    string errorMessage = await ex.Response.Content.ReadAsStringAsync();
    Assert.IsTrue(errorMessage.Contains("My expected error message string"));
    return;
}
Assert.Fail("Expected HttpResponseException didn't get thrown");

This code works, and the test passes.

However, I'd like to better understand understand why my code that reads the error message needs to be constructed this way. The HttpResponseException class only provides async access to its message. I therefore needed to get the message via ReadAsStringAsync(), instead of just being able to synchronously get the message by doing something like ex.Response.Content.Message.

I feel like I might be missing something about why the HttpResponseException class works the way it does. What is the reason that HttpResponseException does not provide synchronous access to its response message?

Jon Schneider
  • 25,758
  • 23
  • 142
  • 170

1 Answers1

4

The HttpResponseException class only provides async access to its message.

HttpResponseException provides you synchronous access to the HTTP response message (Response), which provides you synchronous access to its content (Content). The content of an HTTP stream is what is always read asynchronously. In some uses, the content of an HTTP stream is fully existing in-memory by the time it's used; in other uses, the content of an HTTP stream is streamed over the network.

E.g., if you make an HTTP request with HttpCompletionOption.ResponseHeadersRead, then the response content will be streamed, and it's possible to check the status code and raise an exception before the content of the response actually gets to the box your code is running on.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810