如何处理C#ASP.NET中的拒绝连接错误

sauutmhj  于 2023-04-08  发布在  .NET
关注(0)|答案(1)|浏览(227)

对于以下代码:

public static void Main(string[] args)
    {
        var routingUrl = $"http://localhost:{args[1]}";
        var routingRequest = new HttpRequestMessage(new HttpMethod(args[0]), routingUrl);
        routingRequest.Content = new StringContent("Ping");

        var client = new HttpClient();
        try
        {
            client.Timeout = TimeSpan.FromMilliseconds(1000);
            var httpResponse = client.SendAsync(routingRequest, HttpCompletionOption.ResponseHeadersRead).Result;
        }
        catch (System.AggregateException e)
        {
            Console.WriteLine($"TryPing {routingUrl} fails: {e.Message}");
            Console.WriteLine($"{e.GetType().ToString()}");

            foreach (var errInner in e.InnerExceptions)
            {
                Console.WriteLine(errInner);
            }
        }
    }

我发现可能有几个问题导致catch段运行,例如

  • 发送请求时出错。
  • 连接被拒绝(localhost:xxxxx)

有什么方法可以区分Connection refused错误和其他错误吗?例如:如果异常是由连接被拒绝引起的,则执行某些操作;为其他错误做另一件事?
多谢了!

qij5mzcb

qij5mzcb1#

Catch the httpRequestException instead of aggregateException and check

如果内部异常的类型是aystem.net.aockets.aocketException,则在连接被拒绝时抛出。如果是连接被拒绝错误,则打印出特定的错误消息。如果不是连接被拒绝错误,则打印出一般的错误消息

public static void Main(string[] args)
{
     var routingUrl = $"http://localhost:{args[1]}";
     var routingRequest = new HttpRequestMessage(new HttpMethod(args[0]), 
     routingUrl);
     routingRequest.Content = new StringContent("Ping");

    var client = new HttpClient();
   try
   {
    client.Timeout = TimeSpan.FromMilliseconds(1000);
    var httpResponse = client.SendAsync(routingRequest, 
    HttpCompletionOption.ResponseHeadersRead).Result;
   }
catch (HttpRequestException e)
{
    if (e.InnerException != null && e.InnerException.GetType() == 
         typeof(System.Net.Sockets.SocketException))
    {
        var socketException = 
       (System.Net.Sockets.SocketException)e.InnerException;
        if (socketexception.SocketErrorCode == 
         System.Net.Sockets.SocketError.ConnectionRefused)
        {
            Console.WriteLine($"TryPing {routingUrl} fails: Connection 
            refused");
        }
        else
        {
            Console.WriteLine($"TryPing {routingUrl} fails: {e.Message}");
        }
    }
    else
    {
        Console.WriteLine($"TryPing {routingUrl} fails: {e.Message}");
    }
}

}

相关问题