Rusty Nail
Rusty Nail

Reputation: 2710

Web API Read Response on 400

The Stackoverflow API, if the request is not successful, how to read the response please?

using (HttpClient Client = new HttpClient(handler))
{

    string response = string.Empty;
    response = Client.GetStringAsync(apiUri.Uri).Result;
    return JsonConvert.DeserializeObject<Questions<Question>>(response);
}

When an error occurs:

{"error_id":502,"error_message":"too many requests from this IP, more requests available in 82216 seconds","error_name":"throttle_violation"}

An error InnerException = {"Response status code does not indicate success: 400 (Bad Request)."}

Upvotes: 0

Views: 1345

Answers (1)

tmaj
tmaj

Reputation: 34987

The following paragraph is from Call a Web API From a .NET Client (C#)

HttpClient does not throw an exception when the HTTP response contains an error code. Instead, the IsSuccessStatusCode property is false if the status is an error code. If you prefer to treat HTTP error codes as exceptions, call HttpResponseMessage.EnsureSuccessStatusCode on the response object. EnsureSuccessStatusCode throws an exception if the status code falls outside the range 200–299. Note that HttpClient can throw exceptions for other reasons — for example, if the request times out.

In your case the code could be something like the following.

var response = await client.GetAsync(apiUri.Uri);   
if (!response.IsSuccessStatusCode)
{
    var text = await response.Content.ReadAsStringAsync();
    // Log error
    return null; // throw etc.
}
else 
{
    var text = await response.Content.ReadAsStringAsync();
    var o = JsonConvert.DeserializeObject<Questions<Question>>(o);
    return o;
}   

(You can move var text = ... outside of if if you wish.)


Status code can be examined instead of calling IsSuccessStatusCode, if needed.

if (response.StatusCode != HttpStatusCode.OK) // 200
{
    throw new Exception(); / return null  et.c
}

Upvotes: 3

Related Questions