Skip to content

The response stream from AdvancedResponseWriter is disposed too early #2072

Closed
@bednar

Description

@bednar

Describe the bug
I want to stream response data to my API for advanced processing. For this purpose I use AdvancedResponseWriter because I also want to handle errors from remote resource (=> I cannot use RestSharp.RestClient.DownloadStreamAsync), but the latest changes close response stream too early. It is cause by using in:

using var internalResponse = await ExecuteRequestAsync(request, cancellationToken).ConfigureAwait(false);

To Reproduce

[Test]
public async Task AdvancedResponseWriterKeepStream()
{
    await foreach (var line in MyAsyncApi())
    {
        Console.WriteLine(line);
    }
}

private async IAsyncEnumerable<string> MyAsyncApi()
{
    using var client = new RestClient(new RestClientOptions("https://demo.ckan.org/"));
    var restRequest =
        new RestRequest(
            "dataset/c322307a-b871-44fe-a602-32ee8437ff04/resource/b53c9e72-6b59-4cda-8c0c-7d6a51dad12a/download/sample.csv");

    Stream stream = null;
    restRequest.AdvancedResponseWriter = (response, request) =>
    {
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"Do something with unsuccessful response: {response}");
        }

        stream = response.Content.ReadAsStreamAsync().ConfigureAwait(false).GetAwaiter().GetResult();

        return new RestResponse(request);
    };

    await client.ExecuteAsync(restRequest);

    using var reader = new StreamReader(stream, Encoding.UTF8);
    while (reader.Peek() >= 0)
    {
        // advanced processing
        yield return await reader.ReadLineAsync();
    }
}

Expected behavior
Be able to stream response to API.

Stack trace

System.ArgumentException : Stream was not readable.
   at System.IO.StreamReader..ctor(Stream stream, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean leaveOpen)
   at System.IO.StreamReader..ctor(Stream stream, Encoding encoding)

Desktop (please complete the following information):

  • OS: macOS
  • .NET version: NET 5
  • Version: 110.2.0

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