EnsureSuccessStatusCode should write the response content in the exception if set
We often face issues when using the method EnsureSuccessStatusCode and want to see the reason in application insights.
For example when calling Azure Apis or Apis that uses the APIController then the response message in case of bad requests contains more details what was going wrong.
With the current implementation you only see the statuscode and reasonphrase but not the detailed error that occured.
Example code what should be achieved:
```c#
private static void EnsureSuccessStatusCode(HttpResponseMessage response)
{
if (!response.IsSuccessStatusCode)
{
var responseContent = response.Content == null
? "NoContent"
: response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
throw new HttpRequestException($"{response.StatusCode} (ReasonPhrase: {response.ReasonPhrase}, Content: {responseContent})");
}
}
or Async
```c#
private static async Task EnsureSuccessStatusCodeAsync(HttpResponseMessage response)
{
if (!response.IsSuccessStatusCode)
{
var responseContent = response.Content == null
? "NoContent"
: await response.Content.ReadAsStringAsync();
throw new HttpRequestException($"{response.StatusCode} (ReasonPhrase: {response.ReasonPhrase}, Content: {responseContent})");
}
}
Related to dotnet/runtime#911.
I recognize the need and have been writing similar extensions for HttpResponseMessage in the past. That being said, I don't think it would be a good idea to add this in corefx. A few reasons:
My recommendation would be to author your own extension method for this purpose, since it requires understanding of how the underlying endpoint behaves.
EnsureSuccessStatusCode is a convenience API to quickly inspect an HttpResponseMessage, check for non 2xx responses (failures), and throw an exception.
As noted above, reading the entire HTTP response body content and putting that into an exception message wouldn't be practical. For specialized cases where you want this behavior for diagnostics, it is better to avoid using EnsureSuccessStatusCode and handle the logic yourself.
An extension method would be a great solution if the .NET Framework refrained from using the original. As it is, there's a lot of overhead involved in just getting basic information about a non-success response. The problem details pattern is being implemented in other areas (specifically, the ApiController automatic error responses). EnsureSuccessStatusCode could at least check for the problem details pattern and populate the exception data if it finds a match. This would automatically add that functionality to several Http methods, make them work better with ApiControllers, and save developers a lot of overhead.
Duplicate of https://github.com/dotnet/runtime/issues/911
Triage: Entire response body should not be part of the exception -- status code and potentially its text is fine to be there -- hence the duplicate.