HttpResponseMessage EnsureSuccessStatusCode with Json result

Posted: 2014-05-30 in .Net, My Opinion

Unfortunately EnsureSuccessStatusCode is abit of a let down when it comes to Json rest. Most time Json query will have a descripton in the content on what actually went wrong. The easiest way wround this is to mimic the call and append on the result content with something like below:

public TR Post<T, TR>(Uri requestUri, T data)
{
    using (var client = new HttpClient())
    {
        var serializedData = JsonConvert.SerializeObject(data);

        var result = client.PostAsync(requestUri, new StringContent(serializedData, System.Text.Encoding.UTF8, "application/json")).Result;
        var resultContent = result.Content.ReadAsStringAsync().Result;

        if (!result.IsSuccessStatusCode)
        {
             var responseMessage = "Response status code does not indicate success: " + (int)result.StatusCode + " (" + result.StatusCode + " ). ";
             throw new HttpRequestException(responseMessage + Environment.NewLine + resultContent);
        }
        return JsonConvert.DeserializeObject(resultContent);
    }
}

Gist: https://gist.github.com/ChocoSmith/576af63f0c8c006efaaa

The outputs something like:

Response status code does not indicate success: 400 (BadRequest ). {“Message”:”These are not the driods you are looking for.”}  

 

Cheers

Choco

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s