使用 HttpClient.GetAsync() 时如何确定 404 响应状态

Posted

技术标签:

【中文标题】使用 HttpClient.GetAsync() 时如何确定 404 响应状态【英文标题】:How to determine a 404 response status when using the HttpClient.GetAsync() 【发布时间】:2013-02-01 12:13:01 【问题描述】:

在使用 C# 和 .NET 4.5 出现 404 错误的情况下,我正在尝试确定 HttpClientGetAsync 方法返回的 response

目前我只能判断发生了错误,而不是错误的状态,例如 404 或超时。

目前我的代码我的代码如下所示:

    static void Main(string[] args)
    
        dotest("http://error.123");
        Console.ReadLine();
    

    static async void dotest(string url)
    
        HttpClient client = new HttpClient();

        HttpResponseMessage response = new HttpResponseMessage();

        try
        
            response = await client.GetAsync(url);

            if (response.IsSuccessStatusCode)
            
                Console.WriteLine(response.StatusCode.ToString());
            
            else
            
                // problems handling here
                string msg = response.IsSuccessStatusCode.ToString();

                throw new Exception(msg);
            

        
        catch (Exception e)
        
            // .. and understanding the error here
            Console.WriteLine(  e.ToString()  );                
        
    

我的问题是我无法处理异常并确定其状态和其他问题的详细信息。

我将如何正确处理异常并解释发生了什么错误?

【问题讨论】:

msdn.microsoft.com/en-us/library/system.exception.aspx 看看属性。如果需要打印消息,可以使用e.Message。不确定,你想做什么。 【参考方案1】:

您可以简单地检查响应的StatusCode 属性:

static async void dotest(string url)

    using (HttpClient client = new HttpClient())
    
        HttpResponseMessage response = await client.GetAsync(url);

        if (response.IsSuccessStatusCode)
        
            Console.WriteLine(response.StatusCode.ToString());
        
        else
        
            // problems handling here
            Console.WriteLine(
                "Error occurred, the status code is: 0", 
                response.StatusCode
            );
        
    

【讨论】:

这给了我“在 mscorlib.dll 中发生“System.Net.Http.HttpRequestException”类型的第一次机会异常在 mscorlib.dll 中发生“System.Net.Http.HttpRequestException”类型的异常但未在用户代码中处理”。你知道我可能会错过什么吗?我通过 nuget 加载了 HttpClient 资源,如果它改变了任何东西,因为它在我的 .Net 4.5 中默认没有出现。 有什么例外?是超时吗?如果是这样,您将不得不使用 try/catch 块来处理这种情况。就服务器状态代码而言,您可以按照我的回答进行处理。 "附加信息:发送请求时出错。"是来自输出窗口的唯一其他信息。你指的是这个吗? 是否有 InnerException?异常的类型是什么? 谢谢,是的,在这种情况下错误是超时,您的代码很好地处理了单独的 404 场景。 Try Catch 是超时问题的解决方案。干杯【参考方案2】:

属性response.StatusCode 是一个HttpStatusCode 枚举。

这是我用来取名的代码

if (response != null)

    int numericStatusCode = (int)response.StatusCode;

    // like: 503 (ServiceUnavailable)
    string friendlyStatusCode = $" numericStatusCode  ( response.StatusCode )";

    // ...


或者只报告错误时

if (response != null)

    int statusCode = (int)response.StatusCode;

    // 1xx-3xx are no real errors, while 3xx may indicate a miss configuration; 
    // 9xx are not common but sometimes used for internal purposes
    // so probably it is not wanted to show them to the user
    bool errorOccured = (statusCode >= 400);
    string friendlyStatusCode = "";

    if(errorOccured == true)
    
        friendlyStatusCode = $" statusCode  ( response.StatusCode )";
    
    
    // ....

【讨论】:

以上是关于使用 HttpClient.GetAsync() 时如何确定 404 响应状态的主要内容,如果未能解决你的问题,请参考以下文章

HttpClient.GetAsync,无效的 URI 异常

在 Azure Function 上获取数据时,HttpClient.GetAsync() 会产生 AggregateException

如何确定一个404响应状态使用时,httpclient.getasync

HttpClient.GetAsync 一次只执行 2 个请求?

如何阻止 HttpClient.GetAsync(uri) 挂起? [复制]

HttpClient GetAsync 随机失败