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



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

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

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

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

您可以简单地检查响应的 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
            );
        }
    }
}

属性response.StatusCode是一个 HttpStatusCode 枚举。

这是我用来取一个轻描淡写的名字的代码

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

相关内容

  • 没有找到相关文章

最新更新