重试HttpClient不成功的请求

时间:2013-10-08 23:03:08

标签: c# dotnet-httpclient httpcontent

我正在构建一个给出HttpContent对象的函数,它将发出请求并在失败时重试。但是我得到异常,说HttpContent对象在发出请求后被处理掉。无论如何都要复制或复制HttpContent对象,以便我可以发出多个请求。

 public HttpResponseMessage ExecuteWithRetry(string url, HttpContent content)
 {
  HttpResponseMessage result = null;
  bool success = false;
  do
  {
      using (var client = new HttpClient())
      {
          result = client.PostAsync(url, content).Result;
          success = result.IsSuccessStatusCode;
      }
  }
  while (!success);

 return result;
} 

// Works with no exception if first request is successful
ExecuteWithRetry("http://www.requestb.in/xfxcva" /*valid url*/, new StringContent("Hello World"));
// Throws if request has to be retried ...
ExecuteWithRetry("http://www.requestb.in/badurl" /*invalid url*/, new StringContent("Hello World"));

(显然我不会无限期地尝试,但上面的代码基本上就是我想要的)。

产生此异常

System.AggregateException: One or more errors occurred. ---> System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Http.StringContent'.
   at System.Net.Http.HttpContent.CheckDisposed()
   at System.Net.Http.HttpContent.CopyToAsync(Stream stream, TransportContext context)
   at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at System.Threading.Tasks.Task`1.get_Result()
   at Submission#8.ExecuteWithRetry(String url, HttpContent content)

是否有重复HttpContent对象或重用它?

12 个答案:

答案 0 :(得分:63)

不要实现包装HttpClient的重试功能,而是考虑使用HttpClient构建HttpMessageHandler,在内部执行重试逻辑。例如:

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)
    { }

    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;
    }
}

public class BusinessLogic
{
    public void FetchSomeThingsSynchronously()
    {
        // ...

        // Consider abstracting this construction to a factory or IoC container
        using (var client = new HttpClient(new RetryHandler(new HttpClientHandler())))
        {
            myResult = client.PostAsync(yourUri, yourHttpContent).Result;
        }

        // ...
    }
}

答案 1 :(得分:35)

ASP.NET Core 2.1回答

直接ASP.NET Core 2.1 added support的{p> Polly。这里UnreliableEndpointCallerService是一个在其构造函数中接受HttpClient的类。失败的请求将以指数退避重试,以便下一次重试发生在前一次重试之后的指数级更长的时间内:

services
    .AddHttpClient<UnreliableEndpointCallerService>()
    .AddTransientHttpErrorPolicy(
        x => x.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(3, retryAttempt)));

另外,请考虑阅读我的博文"Optimally Configuring HttpClientFactory"

其他平台回答

此实现使用Polly以指数退避重试,以便下一次重试发生在前一次重试之后的指数级更长的时间内。如果由于超时而引发HttpRequestExceptionTaskCanceledException,它也会重试。 Polly比Topaz更容易使用。

public class HttpRetryMessageHandler : DelegatingHandler
{
    public HttpRetryMessageHandler(HttpClientHandler handler) : base(handler) {}

    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));
}

using (var client = new HttpClient(new HttpRetryMessageHandler(new HttpClientHandler())))
{
    var result = await client.GetAsync("http://example.com");
}

答案 2 :(得分:28)

当前的答案在所有情况下都不会按预期工作,特别是在请求超时的常见情况下(请参阅我的评论)。

此外,他们实施了一种非常天真的重试策略 - 很多时候您需要更多的东西,例如指数退避(这是Azure存储客户端API中的默认设置)。

我在阅读TOPAZ时偶然发现了related blog post(也提供了错误的内部重试方法)。这就是我想出的:

// sample usage: var response = await RequestAsync(() => httpClient.GetAsync(url));
Task<HttpResponseMessage> RequestAsync(Func<Task<HttpResponseMessage>> requester)
{
    var retryPolicy = new RetryPolicy(transientErrorDetectionStrategy, retryStrategy);
    //you can subscribe to the RetryPolicy.Retrying event here to be notified 
    //of retry attempts (e.g. for logging purposes)
    return retryPolicy.ExecuteAsync(async () =>
    {
        HttpResponseMessage response;
        try
        {
            response = await requester().ConfigureAwait(false);
        }
        catch (TaskCanceledException e) //HttpClient throws this on timeout
        {
            //we need to convert it to a different exception
            //otherwise ExecuteAsync will think we requested cancellation
            throw new HttpRequestException("Request timed out", e);
        }
        //assuming you treat an unsuccessful status code as an error
        //otherwise just return the respone here
        return response.EnsureSuccessStatusCode(); 
    });
}

请注意requester委托参数。 应该是HttpRequestMessage,因为您无法多次发送相同的请求。至于策略,这取决于您的用例。例如,瞬态错误检测策略可以简单如下:

private sealed class TransientErrorCatchAllStrategy : ITransientErrorDetectionStrategy
{
    public bool IsTransient(Exception ex)
    {
        return true;
    }
}

至于重试策略,TOPAZ提供三种选择:

  1. FixedInterval
  2. Incremental
  3. ExponentialBackoff
  4. 例如,这里的TOPAZ相当于Azure客户端存储库默认使用的内容:

    int retries = 3;
    var minBackoff = TimeSpan.FromSeconds(3.0);
    var maxBackoff = TimeSpan.FromSeconds(120.0);
    var deltaBackoff= TimeSpan.FromSeconds(4.0);
    var strategy = new ExponentialBackoff(retries, minBackoff, maxBackoff, deltaBackoff);
    

    有关详细信息,请参阅http://msdn.microsoft.com/en-us/library/hh680901(v=pandp.50).aspx

    编辑请注意,如果您的请求包含HttpContent个对象,则您每次都必须重新生成该对象,因为HttpClient也会处理该对象(感谢捕捉Alexandre Pepin)。例如() => httpClient.PostAsync(url, new StringContent("foo")))

答案 3 :(得分:14)

复制StringContent可能不是最好的主意。但简单的修改可以解决问题。只需修改函数并在循环内部创建StringContent对象,如:

public HttpResponseMessage ExecuteWithRetry(string url, string contentString)
{
   HttpResponseMessage result = null;
   bool success = false;
   using (var client = new HttpClient())
   {
      do
      {
         result = client.PostAsync(url, new StringContent(contentString)).Result;
         success = result.IsSuccessStatusCode;
      }
      while (!success);
  }    

  return result;
} 

然后调用它

ExecuteWithRetry("http://www.requestb.in/xfxcva" /*valid url*/, "Hello World");

答案 4 :(得分:3)

这是我使用polly实现的。

nuget

https://www.nuget.org/packages/Microsoft.Extensions.Http.Polly

https://www.nuget.org/packages/Polly

using Polly;
using Polly.Extensions.Http;

//// inside configure service
services.AddHttpClient("RetryHttpClient", c =>
{
    c.BaseAddress = new Uri($"{configuration["ExternalApis:MyApi"]}/");
    c.DefaultRequestHeaders.Add("Accept", "application/json");
    c.Timeout = TimeSpan.FromMinutes(5);
    c.DefaultRequestHeaders.ConnectionClose = true;

}).AddPolicyHandler(GetRetryPolicy());

//// add this method to give retry policy
private static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
{
    return HttpPolicyExtensions
        //// 408,5xx
        .HandleTransientHttpError()
        //// 404
        .OrResult(msg => msg.StatusCode == HttpStatusCode.NotFound)
        //// 401
        .OrResult(msg => msg.StatusCode == HttpStatusCode.Unauthorized)
        //// Retry 3 times, with wait 1,2 and 4 seconds.
        .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
}

答案 5 :(得分:0)

我有几乎相同的问题。 HttpWebRequest queueing library, which guarantees request delivery 我刚刚更新(参见EDIT3)我避免崩溃的方法,但我仍然需要一般机制来保证消息传递(或者在没有传递消息的情况下重新传递)。

答案 6 :(得分:0)

我尝试了它并在使用单元和集成测试时工作。但是,当我实际从REST URL调用时它停滞不前。我发现this interesting post解释了为什么它会卡在这一行。

response = await base.SendAsync(request, cancellationToken);

对此的修复是您最后添加了.ConfigureAwait(false)

response = await base.SendAsync(request, token).ConfigureAwait(false);

我还在这里添加了创建链接令牌部分。

var linkedToken = cancellationToken.CreateLinkedSource();
linkedToken.CancelAfter(new TimeSpan(0, 0, 5, 0));
var token = linkedToken.Token;

HttpResponseMessage response = null;
for (int i = 0; i < MaxRetries; i++)
{
    response = await base.SendAsync(request, token).ConfigureAwait(false);
    if (response.IsSuccessStatusCode)
    {
        return response;
    }
}

return response;

答案 7 :(得分:0)

使用RestEase And Task时,在许多调用(单例)中重用httpClient重试时,它会迷住并抛出TaskCanceledException。 要解决此问题,需要在重试之前Dispose()失败的响应

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)
    { }

    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).ConfigureAwait(false);
            if (response.IsSuccessStatusCode) {
                return response;
            }

            response.Dispose();
        }

        return response;
    }
}

答案 8 :(得分:0)

这建立了已接受的答案,但增加了传递重试次数的能力,并且增加了为每个请求增加无阻塞延迟/等待时间的能力。它还使用try catch来确保重试在发生异常后继续发生。最后,在BadRequests的情况下,我添加了代码以打破循环,您不想多次重新发送相同的错误请求。

public class HttpRetryHandler : DelegatingHandler
{
    private int MaxRetries;
    private int WaitTime;

    public HttpRetryHandler(HttpMessageHandler innerHandler, int maxRetries = 3, int waitSeconds = 0)
        : base(innerHandler)
    {
        MaxRetries = maxRetries;
        WaitTime = waitSeconds * 1000; 
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        HttpResponseMessage response = null;
        for (int i = 0; i < MaxRetries; i++)
        {
            try
            {
                response = await base.SendAsync(request, cancellationToken);
                if (response.IsSuccessStatusCode)
                {
                    return response;
                }
                else if(response.StatusCode == HttpStatusCode.BadRequest)
                {
                    // Don't reattempt a bad request
                    break; 
                }
            }
            catch
            {
                // Ignore Error As We Will Attempt Again
            }
            finally
            {
                response.Dispose(); 
            }

            if(WaitTime > 0)
            {
                await Task.Delay(WaitTime);
            }
        }

        return response;
    }
}

}

答案 9 :(得分:0)

我有同样的问题并解决了。关于“ StringContent” /“ HttpContent”

请查看Amogh Natu的博客,该博客可以帮助我解决此问题

此代码的问题是,第一次调用PostAsync时 制作并失败,则处理httpContent对象。这是 在HttpClient类中设计。请参考此方法中的注释。 尽管这看起来很奇怪,但他们打算这样做,以便用户 不必明确地执行此操作,也可以避免相同的请求 被多次发布。

那么发生的是,当第一个调用失败时,httpContent是 处置,那么由于我们具有重试机制,它会尝试发布 再次调用,现在有一个已处置的对象,因此这次是调用 失败,出现ObjectDisposedException。

解决此问题的一种简单方法是不使用变量进行存储 httpContent,而是直接在创建 呼叫。像这样的东西。

http://amoghnatu.net/2017/01/12/cannot-access-a-disposed-object-system-net-http-stringcontent-while-having-retry-logic/

答案 10 :(得分:-1)

您还可以参考为.NET HttpClient构建瞬态重试处理程序。 访问请参阅KARTHIKEYAN VIJAYAKUMAR帖子。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Net.Http;
using System.Threading;
using System.Diagnostics;
using System.Net;
using Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling;

namespace HttpClientRetyDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var url = "http://RestfulUrl";
            var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, url);

            var handler = new RetryDelegatingHandler
            {
                UseDefaultCredentials = true,
                PreAuthenticate = true,
                Proxy = null
            };

            HttpClient client = new HttpClient(handler);
            var result = client.SendAsync(httpRequestMessage).Result.Content
                .ReadAsStringAsync().Result;

            Console.WriteLine(result.ToString());
            Console.ReadKey();

        }
    }

    /// <summary>
    /// Retry Policy = Error Detection Strategy + Retry Strategy
    /// </summary>
    public static class CustomRetryPolicy
    {
        public static RetryPolicy MakeHttpRetryPolicy()
        {
            // The transient fault application block provides three retry policies
            //  that you can use. These are:
            return new RetryPolicy(strategy, exponentialBackoff);
        }
    }

    /// <summary>
    /// This class is responsible for deciding whether the response was an intermittent
    /// transient error or not.
    /// </summary>
    public class HttpTransientErrorDetectionStrategy : ITransientErrorDetectionStrategy
    {
        public bool IsTransient(Exception ex)
        {
            if (ex != null)
            {
                HttpRequestExceptionWithStatus httpException;
                if ((httpException = ex as HttpRequestExceptionWithStatus) != null)
                {
                    if (httpException.StatusCode == HttpStatusCode.ServiceUnavailable)
                    {
                        return true;
                    }
                    else if (httpException.StatusCode == HttpStatusCode.MethodNotAllowed)
                    {
                        return true;
                    }
                    return false;
                }
            }
            return false;
        }
    }

    /// <summary>
    /// The retry handler logic is implementing within a Delegating Handler. This has a
    /// number of advantages.
    /// An instance of the HttpClient can be initialized with a delegating handler making
    /// it super easy to add into the request pipeline.
    /// It also allows you to apply your own custom logic before the HttpClient sends the
    /// request, and after it receives the response.
    /// Therefore it provides a perfect mechanism to wrap requests made by the HttpClient
    /// with our own custom retry logic.
    /// </summary>
    class RetryDelegatingHandler : HttpClientHandler
    {
        public RetryPolicy retryPolicy { get; set; }
        public RetryDelegatingHandler()
            : base()
        {
            retryPolicy = CustomRetryPolicy.MakeHttpRetryPolicy();
        }


        protected async override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            HttpResponseMessage responseMessage = null;
            var currentRetryCount = 0;
            //On Retry => increments the retry count
            retryPolicy.Retrying += (sender, args) =>
            {
                currentRetryCount = args.CurrentRetryCount;
            };
            try
            {
                await retryPolicy.ExecuteAsync(async () =>
                {
                    responseMessage = await base.SendAsync(request, cancellationToken)
                        .ConfigureAwait(false);
                    if ((int)responseMessage.StatusCode > 500)
                    {
                        // When it fails after the retries, it would throw the exception
                        throw new HttpRequestExceptionWithStatus(
                            string.Format("Response status code {0} indicates server error",
                                (int)responseMessage.StatusCode))
                        {
                            StatusCode = responseMessage.StatusCode,
                            CurrentRetryCount = currentRetryCount
                        };
                    }// returns the response to the main method(from the anonymous method)
                    return responseMessage;
                }, cancellationToken).ConfigureAwait(false);
                return responseMessage;// returns from the main method => SendAsync
            }
            catch (HttpRequestExceptionWithStatus exception)
            {
                if (exception.CurrentRetryCount >= 3)
                {
                    //write to log
                }
                if (responseMessage != null)
                {
                    return responseMessage;
                }
                throw;
            }
            catch (Exception)
            {
                if (responseMessage != null)
                {
                    return responseMessage;
                }
                throw;
            }
        }
    }

    /// <summary>
    /// Custom HttpRequestException to allow include additional properties on my exception,
    /// which can be used to help determine whether the exception is a transient
    /// error or not.
    /// </summary>
    public class HttpRequestExceptionWithStatus : HttpRequestException
    {
        public HttpStatusCode StatusCode { get; set; }
        public int CurrentRetryCount { get; set; }

        public HttpRequestExceptionWithStatus()
            : base() { }

        public HttpRequestExceptionWithStatus(string message)
            : base(message) { }

        public HttpRequestExceptionWithStatus(string message, Exception inner)
            : base(message, inner) { }
    }
}

答案 11 :(得分:-2)

        //Could retry say 5 times          
        HttpResponseMessage response;
        int numberOfRetry = 0;
        using (var httpClient = new HttpClient())
        {
            do
            {
                response = await httpClient.PostAsync(uri, content);
                numberOfRetry++;
            } while (response.IsSuccessStatusCode == false | numberOfRetry < 5);
        }
return response;



        .........