【问题标题】:c# method to continually access web server [duplicate]c#方法不断访问Web服务器[重复]
【发布时间】:2018-08-07 14:40:53
【问题描述】:

我正在使用 c# .NET 配置 IP 摄像机。我正在应用重新启动相机的新固件。重启后,相机主动拒绝连接一段时间,然后进入 503 服务不可用一段时间。

我正在寻找一种可以持续探测相机的方法,忽略 AggregateExceptions 和 503,直到它返回 200/OK。然后继续配置过程。

这是我到目前为止的代码,它会捕获异常,但我希望它继续尝试直到成功。

        var statusDic = new Dictionary<HttpStatusCode, string>();

        try
        {
            using (var client = new HttpClient(new HttpClientHandler
            {
                AutomaticDecompression = DecompressionMethods.GZip,
                Credentials = new NetworkCredential("root", "pass")
            }))
            {
                client.BaseAddress = new Uri($@"http://{dicPair.Value}/axis-cgi/param.cgi");
                var response = client.GetAsync(Source.config);

                while (response.Exception != null || response.Result.StatusCode != HttpStatusCode.OK)
                {
                    Thread.Sleep(5000);
                    response = client.GetAsync(Source.config);
                }

                statusDic.Add(response.Result.StatusCode, response.Result.ToString());
            }
        }
        catch (WebException ex)
        {
            using (var sr =
                new StreamReader(ex.Response.GetResponseStream() ?? throw new InvalidOperationException()))
            {
                Logger.LogError(sr.ReadToEnd());
            }
        }
        catch (AggregateException ex)
        {
            Logger.LogError(ex.Message);
        }

        return statusDic;

【问题讨论】:

  • 添加一个while 和一个布尔值..
  • 我可能会使用您的代码创建一个计时器作为经过的事件。也许间隔 5 秒?
  • 像拒绝服务攻击?或者比这更慢,比如一个带有Task.Delay() 的循环来节流?

标签: c# .net winforms dotnet-httpclient


【解决方案1】:

在我们的项目中有类似的案例,我们使用Polly库https://github.com/App-vNext/Polly

它非常灵活、基于规则、NuGet 可用、BSD 许可等。鉴于此,您无需重新发明自行车。

您可以查看 Scott Hanselman 撰写的这篇关于 Polly 实际使用情况的精彩帖子:https://www.hanselman.com/blog/AddingResilienceAndTransientFaultHandlingToYourNETCoreHttpClientWithPolly.aspx

【讨论】:

    【解决方案2】:

    这就是代码现在的样子(感谢几个人的想法):

    var statusDic = new Dictionary<HttpStatusCode, string>();
            Task<HttpResponseMessage> response;
            var client = new HttpClient(new HttpClientHandler
            {
                AutomaticDecompression = DecompressionMethods.GZip,
                Credentials = new NetworkCredential("root", "pass")
            });
    
            try
            {
                client.BaseAddress = new Uri($@"http://{dicPair.Value}/axis-cgi/param.cgi");
    
                while (true)
                {
                    response = client.GetAsync(Source.config);
                    if (response.Result.IsSuccessStatusCode)
                        break;
                    Task.Delay(5000);
                }
    
                statusDic.Add(response.Result.StatusCode, response.Result.ToString());
            }
            catch (WebException ex)
            {
                using (var sr =
                    new StreamReader(ex.Response.GetResponseStream() ?? throw new InvalidOperationException()))
                {
                    Logger.LogError($@"WEB EXCEPTION - {sr.ReadToEnd()}");
                    statusDic.Add(HttpStatusCode.BadRequest, sr.ReadToEnd());
                }
            }
            catch (AggregateException ex)
            {
                Logger.LogDebug($@"AGGREGATE EXCEPTION - {ex.InnerExceptions}");
                while (true)
                {
                    response = client.GetAsync(Source.config);
                    if (response.Result.IsSuccessStatusCode)
                        break;
                    Task.Delay(5000);
                }
    
                statusDic.Add(response.Result.StatusCode, response.Result.ToString());
            }
    
            return statusDic;
    

    到目前为止,这似乎奏效了。谢谢大家!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-19
      • 1970-01-01
      • 1970-01-01
      • 2018-08-01
      相关资源
      最近更新 更多