Quantcast
Channel: Active questions tagged retry-logic - Stack Overflow
Viewing all articles
Browse latest Browse all 950

The stream was already consumed. It cannot be read again error using Polly to retry requests C# .NET 6

$
0
0

I read this 'Stream was already consumed' error using Polly to retry requests in ASP.NET Core but cannot see where to clone the http request message.

So in my code, I register httpclient like:

var httpClientBuilder = serviceCollection.AddHttpClient("CustomHttpClientName");httpClientBuilder.AddHttpMessageHandler(ctx=>...)httpClientBuilder.AddPolicyHandler(GetRetryPolicy());
private static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy(){    return HttpPolicyExtensions.HandleTransientHttpError()        .OrResult(result => !result.IsSuccessStatusCode)        .OrResult(result =>        {            var elem = result.Content.ReadFromJsonAsync<JsonElement>().GetAwaiter().GetResult();            return elem.TryGetProperty("error", out _);        })        .WaitAndRetryAsync(            sleepDurations: Backoff.DecorrelatedJitterBackoffV2(medianFirstRetryDelay: TimeSpan.FromSeconds(1), retryCount: 3),            onRetry: (outcome, timespan, retryCount, context) =>            {                context.GetLogger()?.LogWarning("Delaying for {Delay}ms, then making retry {Retry}.", timespan.TotalMilliseconds, retryCount);            });}

and then http client call:

var request = CreateRequest(jsonContent, HttpMethod.Post, uri);await GetClient().SendAsync(request, cancellationToken); // here I get runtime exception

I want to do a retry if in response json I see error field.

Above code leads to InvalidOperationException: 'The stream was already consumed. It cannot be read again'


Viewing all articles
Browse latest Browse all 950

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>