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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14646052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:34:56  来源:igfitidea点击:

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

c#exception-handlinghttpclient.net-4.5async-await

提问by Gga

I am trying to determine the responsereturned by HttpClient's GetAsyncmethod in the case of 404 errors using C# and .NET 4.5.

我想,以确定response由归国HttpClientGetAsync使用C#和.NET 4.5的404错误的情况下,方法。

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?

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

采纳答案by Darin Dimitrov

You could simply check the StatusCodeproperty 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
            );
        }
    }
}