Search code examples
c#blazorblazor-webassemblydotnet-httpclient

How to get status code of the response from web service call


I am trying to troubleshoot the response object I get from the web service call.

When I try response.StatusCode in ItemService.cs. Says

does not contain definition for 'Statuscode'. Are you missing directive or assembly reference.

I would appreciate if anyone could advise me on how to catch the exact response code and error message.

ItemService.cs

public async Task<List<Item>> GetItems()
{
    var response = await _httpClient.GetFromJsonAsync<List<Item>>("api/item");
    if(response.StatusCode)// error
    {}
}

Solution

  • You need to use HttpClient.GetAsync method to return the value of Task<HttpResponseMessage>.

    In the HttpResponseMessage class, it contains StatusCode property which is what you need.

    Updated: To check whether the response returns a success code, you should use the IsSuccessStatusCode property. Otherwise, you should compare the status code below:

    if (response.StatusCode != HttpStatusCode.OK)
    

    Next, extract the content from the HttpResponseMessage with HttpContentJsonExtensions.ReadFromJsonAsync method.

    public async Task<List<Item>> GetItems()
    {
        var response = await _httpClient.GetAsync("api/Item");
    
        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine(response.StatusCode);
    
            return new List<Item>();
        }
    
        return await response.Content.ReadFromJsonAsync<List<Item>>();
    }
    

    Reference

    Make HTTP requests using IHttpClientFactory in ASP.NET Core (CreateClient section with demo)