Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/libraries/System.Net.Http/src/System/Net/Http/HttpContent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1103,12 +1103,22 @@ public override void Write(byte[] buffer, int offset, int count)

public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled(cancellationToken);
}

Write(buffer, offset, count);
return Task.CompletedTask;
}

public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
if (cancellationToken.IsCancellationRequested)
{
return ValueTask.FromCanceled(cancellationToken);
}

Write(buffer.Span);
return default;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -596,6 +596,32 @@ await server.AcceptConnectionAsync(async connection =>
});
}

[Fact]
public async Task GetAsync_WithCustomHandlerReturningStringContent_PreCanceledToken_ThrowsTaskCanceledException()
{
// Regression test for https://github.com/dotnet/runtime/issues/121996
// Ensures that when using a custom handler that returns pre-buffered content (StringContent),
// calling GetAsync with a pre-canceled token properly throws TaskCanceledException
using var handler = new CustomHandler();
using var httpClient = new HttpClient(handler);
var cts = new CancellationTokenSource();
cts.Cancel();

await Assert.ThrowsAsync<TaskCanceledException>(() =>
httpClient.GetAsync("https://example.com", cts.Token));
}

private sealed class CustomHandler : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return Task.FromResult(new HttpResponseMessage()
{
Content = new StringContent("Hello from CustomHandler")
});
}
}

[Theory]
[InlineData(true)]
[InlineData(false)]
Expand Down