【问题标题】:How can I safely throw exceptions from within a DelegatingHandler如何安全地从 DelegatingHandler 中抛出异常
【发布时间】:2018-04-19 13:00:55
【问题描述】:

我有一个委托处理程序,它根据从服务器接收到的错误消息引发特定异常。 这允许客户端重试(使用 polly,但正如您将看到的机制并不重要) 在两次尝试失败后,第三次尝试只是挂起。没有数据到达服务器,也没有进一步的事情发生。这似乎是因为 HttpClient 最多有两个连接,这表明这些连接没有正确关闭。 我可以做些什么来关闭连接还是应该更改设计以使委托处理程序不会引发异常?

查看下面的简单示例以重现

private class Test : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var response = await base.SendAsync(request, cancellationToken);

        throw new Exception("afesaf");
    }
}

[HttpGet]
[Route("B")]
public async Task B()
{
    var handler = new HttpClientHandler();
    var pipeline = HttpClientFactory.CreatePipeline(handler, new[] { new Test() });

    var http = new HttpClient(pipeline);

    http.BaseAddress = new Uri("http://google.com");

    var count = 0;
    while (count++ < 5)
    try
    {
        Log.Info("A");
        var request = new HttpRequestMessage(HttpMethod.Get, "");
        await http.SendAsync(request, HttpCompletionOption.ResponseContentRead, CancellationToken.None).ConfigureAwait(false);
    }
    catch
    {

    }
}

【问题讨论】:

    标签: c# httpclient


    【解决方案1】:

    处置响应对象。

    我在委托处理程序中使用了以下内容,因为我有多个可能在实际代码中引发异常的点

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        HttpResponseMessage response = null;
        try
        {         
            response = await base.SendAsync(request, cancellationToken);
            throw new Exception("afesaf");
        } 
        catch
        {
            response?.Dispose();
            throw 
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2011-01-24
      • 2013-11-30
      • 1970-01-01
      相关资源
      最近更新 更多