Skip to content

[Bug]: Transport failure while buffering the response body is swallowed and reported as a deserialization error #2359

Closed

Description

@HulinCedric

Describe the bug 🐞

When the connection fails while the response body is being downloaded, Refit reports a deserialization error and the transport exception is lost.

RequestExecutionHelpers.TryBufferContentAsync (buffering added in #1705, cancellation propagated in #2284) discards non-cancellation failures of LoadIntoBufferAsync as best-effort. For a response coming from the network this cannot recover: the failed buffering has already consumed the content stream, so the serializer's read throws InvalidOperationException. The caller gets:

Refit.ApiException: An error occured deserializing the response.
System.InvalidOperationException: The stream was already consumed. It cannot be read again.

The IOException from the transport appears nowhere in the exception chain. The same happens with Task<ApiResponse<T>>: response.Error carries the same chain.

As a result, a network failure looks like a contract or deserialization bug, and resilience policies that retry transient transport errors do not recognise it.

Step to reproduce

Self-contained console app (net10.0, Refit 16.3.0). A local server sends the headers and the start of a JSON body, then resets the connection:

using System.Net;
using System.Net.Sockets;
using System.Text;
using Refit;

var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
_ = Task.Run(async () =>
{
    using var socket = await listener.AcceptSocketAsync();
    await socket.ReceiveAsync(new byte[4096]);
    await socket.SendAsync(Encoding.ASCII.GetBytes(
        "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 1000\r\n\r\n{\"name\":\"par"));
    await Task.Delay(200);
    socket.LingerState = new LingerOption(true, 0); // close with RST
    socket.Close();
});

var api = RestService.For<IItemsApi>(new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{port}") });

try
{
    await api.GetItem();
}
catch (Exception exception)
{
    for (var current = exception; current is not null; current = current.InnerException)
        Console.WriteLine($"{current.GetType().FullName}: {current.Message}");
}

public interface IItemsApi
{
    [Get("/item")]
    Task<Item> GetItem();
}

public record Item(string Name);

Output:

Refit.ApiException: An error occured deserializing the response.
System.InvalidOperationException: The stream was already consumed. It cannot be read again.

Note: a test double returning StreamContent does not reproduce it, because StreamContent lets the serializer read the same underlying stream again. The network content (HttpConnectionResponseContent) can only be read once.

Expected behavior

The transport failure is visible to the caller, for example:

  • the exception thrown by LoadIntoBufferAsync is propagated (like a failure during SendAsync, which surfaces as ApiRequestException / HasRequestError), at least when the content cannot be read again after the failed buffering; or
  • it becomes the inner exception of the thrown ApiException, instead of the follow-up InvalidOperationException.

IDE

Rider Windows

Operating system

Windows 11 (repro), Linux (production)

Refit Version

16.3.0

Additional information ℹ️

Related: #1384, #1705, #2284.

Activity

  1. github-actions commented on Nov 16, 2026

    @github-actions

    This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

  2. locked and limited conversation to collaborators on Nov 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions