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

Gga*_*Gga 29 c# exception-handling httpclient async-await .net-4.5

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

目前我只能说出错误已经发生而不是错误的状态,如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()  );                
        }
    }
Run Code Online (Sandbox Code Playgroud)

我的问题是我无法处理异常并确定其状态以及出错的其他详细信息.

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

Dar*_*rov 46

您只需检查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
            );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 有什么例外?是超时吗?如果是这样,你将不得不使用try/catch块来处理这种情况.就服务器状态代码而言,您可以处理它们,如我的答案中所示. (3认同)