Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

c# - How to implement an HTTP GET for large data avoiding Request Timeout error

I`m developing WebAPI to transfer data between 2 systems. Simplifying I have to implement an HTTP GET method to retrieve large data. Same problem for a POST method to push data.

How can I do to avoid timeout error due to long processing?

Any help will be appreciated :)

Thanks

question from:https://stackoverflow.com/questions/66052431/how-to-implement-an-http-get-for-large-data-avoiding-request-timeout-error

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For resuming problem I used Polly See below:

  public class RetryHandler : DelegatingHandler
  {
    // Strongly consider limiting the number of retries - "retry forever" is
    // probably not the most user friendly way you could respond to "the
    // network cable got pulled out."
    private const int MaxRetries = 3;

    public RetryHandler(HttpMessageHandler innerHandler)
        : base(innerHandler)
    { }

    // It doesn't work with Transient timeouts
    ////protected override async Task<HttpResponseMessage> SendAsync(
    ////    HttpRequestMessage request,
    ////    CancellationToken cancellationToken)
    ////{
    ////  HttpResponseMessage response = null;
    ////  for (int i = 0; i < MaxRetries; i++)
    ////  {
    ////    response = await base.SendAsync(request, cancellationToken);
    ////    if (response.IsSuccessStatusCode)
    ////    {
    ////      return response;
    ////    }
    ////  }

    ////  return response;
    ////}
    ///

    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken) =>
        Policy
            .Handle<HttpRequestException>()
            .Or<TaskCanceledException>()
            .OrResult<HttpResponseMessage>(x => !x.IsSuccessStatusCode)
            .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(3, retryAttempt)))
            .ExecuteAsync(() => base.SendAsync(request, cancellationToken));
  }

I pass RetryHandler into HttpClient object:

this.Client = new HttpClient(new RetryHandler(new HttpClientHandler()))
      {
        BaseAddress = new Uri(uriText)
      };

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...