dotnet / dotnet/extensions

AddStandardResilienceHandler doesn't catch HttpRequestException for content length errors.

Open
#6,071 0 comments 0 reactions 0 assignees View on GitHub
area-resilience bug untriaged
Dominant language
C#
Stars
3.2k
Forks
894
Avg merge
1d 12h
Merged PRs (30d)
23

Description

### Description

If the API request fails due to a content length mismatch (specifically header Content-Length > than content), we get the following exception `System.Net.Http.HttpRequestException: Error while copying content to a stream.`, however it is not caught by the resilience pipeline.

My understanding is that the extension method(s) inject a DelegatingHandler to wrap the API request and attempt to detect errors and apply the resilience pipeline accordingly. However, the above exception does not get triggered during the DelegatingHandler unless the content is explicitly read within the handler and therefore the pipeline is never applied.

### Reproduction Steps

Client:
```
using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();

services.AddHttpClient("my-client")
.AddStandardResilienceHandler();

// Use the client
HttpClient client = services.BuildServiceProvider()
.GetRequiredService()
.CreateClient("my-client");

// Make resilient HTTP request
HttpResponseMessage response = await client.GetAsync("http://localhost:5174/badlength");
```

Server:
```
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/badlength", (HttpContext context) =>
{
const string content = "This is the response content";
var incorrectContentLength = content.Length + 10; // Set an incorrect content length

context.Response.Headers["Content-Length"] = incorrectContentLength.ToString();
return content;
});

app.Run();
```

### Expected behavior

The HttpRequestException should be caught and retried given it's declared in the policy to retry the exception type.

### Actual behavior

The HttpRequestException is not caught and is thrown to the client program immediately.

### Regression?

_No response_

### Known Workarounds

_No response_

### Configuration

.net 8.0 + Windows 11

### Other information

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.