0

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
    {}
}

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Using if (System.Convert.ToBoolean(response.StatusCode)) worked. Tweaking the code as edited above, Helped.
Hi, I update my answer for the checking StatusCode part. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.