How to determine a 404 response status when using the HttpClient.GetAsync()

后端 未结 2 1138
情歌与酒
情歌与酒 2020-12-09 07:54

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.

相关标签:
2条回答
  • 2020-12-09 08:18

    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
                );
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-09 08:27

    The property response.StatusCode is an HttpStatusCode enum.

    This is the code I use to get a friedly name for the user

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

    Or when only errors should be reported

    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 })";
        }
    
        // ....
    }
    
    0 讨论(0)
提交回复
热议问题