简体   繁体   English

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

[英]How to determine a 404 response status when using the HttpClient.GetAsync()

I am trying to determine the response returned by HttpClient 's GetAsync method in the case of 404 errors using C# and .NET 4.5.我正在尝试使用 C# 和 .NET 4.5 确定在出现 404 错误的情况下HttpClientGetAsync方法返回的response

At present I can only tell that an error has occurred rather than the error's status such as 404 or timeout.目前我只能判断发生了错误,而不能判断错误的状态,例如 404 或超时。

Currently my code my code looks like this:目前我的代码我的代码如下所示:

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

My problem is that I am unable to handle the exception and determine its status and other details of what went wrong.我的问题是我无法处理异常并确定其状态和其他出错细节。

How would I properly handle the exception and interpret what errors occurred?我将如何正确处理异常并解释发生了什么错误?

You could simply check the StatusCode property of the response:您可以简单地检查响应的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
            );
        }
    }
}

The property response.StatusCode is a HttpStatusCode enum.属性response.StatusCode是一个HttpStatusCode枚举。

This is the code I use to get a friedly name这是我用来获得油炸名称的代码

if (response != null)
{
    int numericStatusCode = (int)response.StatusCode;

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

    // ...

}

Or when only errors should be reported或者只报告错误时

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 })";
    }
    
    // ....
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 httpClient.GetAsync 时添加标头 - Adding headers when using httpClient.GetAsync 当我使用线程运行 HttpClient.GetAsync(...) 并且它永远不会返回响应 - When I using a thread to run HttpClient.GetAsync(...) and it never returns response HttpClient.GetAsync(...) 在使用 await/async 时永远不会返回 - HttpClient.GetAsync(…) never returns when using await/async 使用 HttpClient.GetAsync().Result 时返回什么类型; - what type returned when using HttpClient.GetAsync().Result; 当没有互联网连接时,HttpClient.GetAsync(...)“死锁” - HttpClient.GetAsync(…) “deadlock” when there is no internet connection 使用httpClient.GetAsync()后无法从方法返回HTTP状态和数据 - Can't return HTTP status and data from a method after using httpClient.GetAsync() HttpClient.GetAsync 与网络凭据 - HttpClient.GetAsync with network credentials 用户未登录时HttpClient.GetAsync上的System.IO.IOException - System.IO.IOException on HttpClient.GetAsync when user is not logged in 连接到VPN时,HttpClient.GetAsync超时 - HttpClient.GetAsync times out when connected to VPN 使用HttpClient.GetAsync来调用Web API似乎挂了 - Using HttpClient.GetAsync to call Web API seems to hang
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM