What does EnsureSuccessStatusCode do?
[C#, .NET, HttpClient]
When making web requests using a HttpClient, you almost certainly would use one of these methods:
For niche usages, you might also use
For example:
// fetch a byte array
_ = await client.GetByteArrayAsync("https://conradakunga.com");
// fetch a stream
_ = await client.GetStreamAsync("https://conradakunga.com");
// fetch a string
_ = await client.GetStringAsync("https://conradakunga.com");
What they have in common is that they will throw an Exception
- a HttpRequestException in particular, if a non-success response code is returned.
A non-success here is anything not in the 200 range.
Now let us try the lower level method GetAsync, for a URL I know for a fact does not exist:
var client = new HttpClient();
client.Timeout = TimeSpan.FromSeconds(250);
try
{
// fetch a response
var response = await client.GetAsync("https://conradakunga.com/324234");
}
catch (Exception ex)
{
Console.WriteLine($"There was an error: {ex.Message}");
}
This code does not throw an exception!
The response here is a HttpResponseMessage object. You can interrogate this to see what happened.
try
{
// fetch a response
var response = await client.GetAsync("https://conradakunga.com/324234");
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Success");
}
else
{
Console.WriteLine($"Error fetching the page, server returned a {response.StatusCode}");
}
}
catch (Exception ex)
{
Console.WriteLine($"There was an error: {ex.Message}");
}
This will print the following:
Error fetching the page, server returned a NotFound
As I have pointed out in a previous post about fetching JSON, this technique is more flexible because, in cases where the failure reason is returned in the response, you can read this yourself from the Content property of the HttpResponseMessage
object.
This is not possible using any of the other techniques.
If, however, you want GetAsync
to behave like the others, you can call the EnsureSuccessStatusCode method.
This code, for example, will throw an exception:
try
{
// fetch a response
var response = await client.GetAsync("https://conradakunga.com/324234");
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Success");
}
else
{
Console.WriteLine($"Error fetching the page, server returned a {response.StatusCode}");
}
}
catch (Exception ex)
{
Console.WriteLine($"There was an error: {ex.Message}");
}
The code for checking the response status code will never be executed if an exception occurs.
TLDR
The EnsureSuccessStatusCode
method can be used to signal to the GetAsync
method to throw an exception if the response is not a success.
Happy hacking!