Last night I had some time to look over a project that is on CodePlex. There I found the following code:
Well, there is a check if the return code was 200 (OK) and if not, throw an exception.
This is not the wrong way to go, but you should know that HttpClient already contains a method that can check if the return code was 200 (OK). This method will throw an exception automatically if the return code is not the expected one.
The above code could be written in the following way:
The most important thing is to know the available API when you start to use different core features.
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = fooUrl;
FooMessage message = new FooMessage()
{
...
}
Task<HttpResponseMessage> response = httpClient.PostAsJsonAsync("api/foo", message);
response.Wait();
if (response.Result.StatusCode != HttpStatusCode.OK)
{
throw new Exception("...");
}
}
What do you see strange in this code?Well, there is a check if the return code was 200 (OK) and if not, throw an exception.
This is not the wrong way to go, but you should know that HttpClient already contains a method that can check if the return code was 200 (OK). This method will throw an exception automatically if the return code is not the expected one.
The above code could be written in the following way:
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = fooUrl;
FooMessage message = new FooMessage()
{
...
}
Task<HttpResponseMessage> response = httpClient.PostAsJsonAsync("api/foo", message);
response.Wait();
response.Result.EnsureSuccessStatusCode();
}
If you wouldn't want to throw an exception, only to check if the status code was okay you could also use the property IsSuccessStatusCode of the result.The most important thing is to know the available API when you start to use different core features.
The two codes are not equivalent, guess why? :)
ReplyDelete(depending on the problem, the first or the second one might be buggy, or none)