如何确定一个404响应状态使用HttpClient.GetAsync时()(How to deter

2019-07-19 03:43发布

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

目前我只能告诉发生了一个错误,而不是错误的状态,如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()  );                
        }
    }

我的问题是,我无法处理异常,并确定其状态和什么地方出了错其他细节。

我将如何妥善处理异常,并解释发生了什么错误?

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


文章来源: How to determine a 404 response status when using the HttpClient.GetAsync()