In almost every application today you need to interact with REST api's typically using JSON as the serialisation format.
During some code reviews I noticed the following boilerplate code coming back:
public async Task<Product> GetProduct(string uri, HttpClient httpClient) | |
{ | |
using var httpResponse = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead); | |
httpResponse.EnsureSuccessStatusCode(); | |
if (httpResponse.Content is object && httpResponse.Content.Headers.ContentType.MediaType == "application/json") | |
{ | |
var contentStream = await httpResponse.Content.ReadAsStreamAsync(); | |
try | |
{ | |
return await System.Text.Json.JsonSerializer.DeserializeAsync<Product>(contentStream, new System.Text.Json.JsonSerializerOptions { IgnoreNullValues = true, PropertyNameCaseInsensitive = true }); | |
} | |
catch (JsonException ex) | |
{ | |
_logger.LogError(ex, "Error fetching product."); | |
} | |
} | |
return null; | |
} |
Although there is nothing wrong with the code above, it is code that you don't have to write yourself. As this is such a common scenario, Microsoft created the System.Net.Http.Json NuGet package with the release of .NET 5.0. This package contains extension methods on the HttpClient object that take care of a variety of scenarios for you, including handling the content stream, validating the content media type and handling the deserialization.
Using this package, you no longer need to write all this logic yourself and you can rewrite the code above to the following:
public async Task<Product> GetProduct(string uri, HttpClient httpClient) | |
{ | |
try | |
{ | |
return await httpClient.GetFromJsonAsync<User>(uri); | |
} | |
catch (JsonException) | |
{ | |
_logger.LogError(ex, "Error fetching product."); | |
} | |
return null; | |
} |
Hope that helps!