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

C# 如何在使用HttpClient.GetAsync()时确定404响应状态,c#,exception-handling,httpclient,.net-4.5,async-await,C#,Exception Handling,Httpclient,.net 4.5,Async Await,在使用C#和.NET 4.5出现404错误的情况下,我试图确定由HttpClient的GetAsync方法返回的响应 目前,我只能判断是否发生了错误,而不能判断错误的状态,如404或超时 当前我的代码我的代码如下所示: static void Main(string[] args) { dotest("http://error.123"); Console.ReadLine(); } static async void dotes

在使用C#和.NET 4.5出现404错误的情况下,我试图确定由
HttpClient
GetAsync
方法返回的
响应

目前,我只能判断是否发生了错误,而不能判断错误的状态,如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()  );                
        }
    }
我的问题是,我无法处理异常并确定其状态以及出错的其他细节


如何正确处理异常并解释发生的错误?

您只需检查响应的属性即可:

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

属性
response.StatusCode
是一个枚举

这是我用来获取friedly名称的代码

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

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

    // ...

}
或者只报告错误

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

请看属性。如果需要打印邮件,可以使用
e.message
。不确定,您正在尝试执行什么操作。这给了我“在mscorlib.dll中出现'System.Net.Http.HttpRequestException'类型的第一次机会异常在mscorlib.dll中出现'System.Net.Http.HttpRequestException'类型的异常,但在用户代码中未处理”。你知道我错过了什么吗?如果HttpClient资源在默认情况下没有出现在我的.NET4.5中,那么我通过nuget加载了它,这会改变什么呢?是超时吗?如果是这样,您将不得不使用try/catch块来处理这种情况。就服务器状态代码而言,您可以按照我的回答中所示处理它们。“其他信息:发送请求时出错。”是输出窗口中唯一的其他信息。这就是你所指的吗?是否存在内部异常?异常的类型是什么?谢谢,是的,在这种情况下错误是超时的,您的代码很好地处理了一个单独的404场景。Try-Catch是超时问题的解决方案。干杯