使用 HttpClient.GetAsync() 时如何确定 404 响应状态 [英] How to determine a 404 response status when using the HttpClient.GetAsync()

查看:36
本文介绍了使用 HttpClient.GetAsync() 时如何确定 404 响应状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

At present I can only tell that an error has occurred rather than the error's status such as 404 or timeout.

目前我的代码是这样的:

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?

推荐答案

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

You could simply check the StatusCode property of the response:

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

这篇关于使用 HttpClient.GetAsync() 时如何确定 404 响应状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆