.Net Core 3.0 onwards Microsoft brought up a new package called System.Net.Http.Json. This new package provides JSON extension methods for HttpClient. These JSON extension methods will have a prebuild mechanism for serializing or deserializing response data or payload of HttpClient call.
System.Net.Http.Json extension methods that are provided to HttpClient, few of them are mentioned below.
- GetFromJsonAsync
- PostAsJsonAsync
- PutAsJsonAsync
- ReadFromJsonAsync
Create A .Net Core Web API Sample Application:
Let's create a .Net Core sample Web API application, from this application we will consume another Web API by implementing HttpClient calls. We can create a Web API sample application using IDE like Visual Studio 2019(Supports .Net Core 3.0 plus) or Visual Studio Code.
Create A Typed Client:
In .Net Core using the HttpClientFactory approach, we can write HttpClient calls in different methods, where Typed Client is one such method. In the Typed Client approach, one class will be defined for one type of external domain, where we will implement all GET or POST calls for that domain in that specified class. So in this sample, I'm using Typed Client.
Let's consume any Web API into our newly created sample application. To explain this example I have created a sample Web API project which returns Todo Items(so to follow my steps please create one sample API project which returns some data, because I'm not explaining here about my Todo endpoint).
Let's start with creating a response object model(ex:- TodoItem).
Models/TodoItem.cs:
public class TodoItem { public int id { get; set; } public string itemNames { get; set; } }Now let's add Typed Client.
Clients/TodoClient:
using System.Net.Http; using System; using System.Threading.Tasks; using System.Collections.Generic; using httpjson.sample.api.Models; using System.Text.Json; namespace httpjson.sample.api.Clients { public class TodoClient { private readonly HttpClient _httpClient; public TodoClient(HttpClient httpClient) { httpClient.BaseAddress = new Uri("https://localhost:44379/"); _httpClient = httpClient; } public async Task<List<TodoItem>> GetTodos() { var response = await _httpClient.GetAsync("/api/todo/get-all"); response.EnsureSuccessStatusCode(); string data = await response.Content.ReadAsStringAsync(); return JsonSerializer.Deserialize<List<TodoItem>>(data); } } }
- #L12 at this line HttpClient is injected by HttpClientFactory.
- #L13 at this line defining base address, nothing but a domain. So all API call implementation in this Typed Client class belongs to that domain(localhost:44379 my custom API I'm consuming in this sample, please create your own endpoint to follow my steps).
- #L18-L24 these lines define get API call.
- #L22 at this line response is reading as a string
- #L23 at this line response is deserialized to object.
Startup.cs:
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddHttpClient<TodoClient>(); }Let's add test controller which calls API in Typed Client.
Controllers/TestController.cs:
using System.Threading.Tasks; using httpjson.sample.api.Clients; using Microsoft.AspNetCore.Mvc; namespace httpjson.sample.api.Controllers { [ApiController] [Route("[controller]")] public class TestController : ControllerBase { private readonly TodoClient _todoClient; public TestController(TodoClient todoClient) { _todoClient = todoClient; } [HttpGet] [Route("get-all-todo")] public async Task<IActionResult> GetTodos() { return Ok(await _todoClient.GetTodosWithJsonExtension()); } } }Now run the application and test the API.
Finally, successfully we have created API which consumes other API, everything till now we did is a common approach. In upcoming steps, we going to use JSON extension methods and refactor the above code using them.
Install System.Net.Http.Json Package:
System.Net.Http.Json not bundled with .Net Core Framework needs to install an external package.
Package Manager Install-Package System.Net.Http.Json
.Net CLI dotnet add package System.Net.Http.Json
Use ReadFromJsonAsync Extension Method:
ReadFromJsonAsync is an extension method on HttpResponseMessage.Content. Using this method we can avoid explicitly reading the response as string or stream. It also avoids explicit deserialization of response to the output object.
Let's update the code in Typed Client to use the ReadFromJsonAsync method.
Clients/TodoClient.cs:
public async Task<List<TodoItem>> GetTodos() { var response = await _httpClient.GetAsync("/api/todo/get-all"); response.EnsureSuccessStatusCode(); // string data = await response.Content.ReadAsStringAsync(); // return JsonSerializer.Deserialize<List<TodoItem>>(data); return await response.Content.ReadFromJsonAsync<List<TodoItem>>(); }#L7 at this line ReadFromJsonAsync reads the response from content and convert to the output object.
#L5-L6 at this line commented code of old implementation.
Use GetFromJsonAsync Extension Method:
GetFromJsonAsync is an extension method on HttpClient. Using this method it will avoid all traditional functionality like invoking API, reading response, and converting response type to the output object. It is a single line code.
Let's update the code int Typed Client to use the GetFromJsonAsync method.
Clients/TodoClient.cs:
public async Task<List<TodoItem>> GetTodos() { return await _httpClient.GetFromJsonAsync<List<TodoItem>>("/api/todo/get-all"); //var response = await _httpClient.GetFromJsonAsync("/api/todo/get-all"); // response.EnsureSuccessStatusCode(); // string data = await response.Content.ReadAsStringAsync(); // return JsonSerializer.Deserialize<List<TodoItem>>(data); }#L3 at this line GetFromJsonAsync methods invokes API call, reads the response, and then converts the response to the output object type.
#L4-L7 at this line commented old implementation code.
HttpClient Post:
Let's write a sample code for the post method for HttpClient.
Clients/TodoClients.cs:
public async Task PostTodo(TodoItem todo) { var postData = new StringContent(JsonSerializer.Serialize(todo),Encoding.UTF8,"application/json"); var response = await _httpClient.PostAsync("/api/todo/save",postData); response.EnsureSuccessStatusCode(); }#L3 at this line we can observe post object serialized before sending to API call.
Use PostAsJsonAsync Extension Method:
PostAsJsonAsync is an extension method on HttpClient. This method will automatically serialize post data and invoke API calls. It is a single line code.
Let's update the HttpClient post method to use the PostAsJsonAsync extension method.
Clients/TodoClient.cs:
public async Task PostTodo(TodoItem todo) { await _httpClient.PostAsJsonAsync("/api/todo/save",todo); // var postData = new StringContent(JsonSerializer.Serialize(todo),Encoding.UTF8,"application/json"); // var response = await _httpClient.PostAsync("/api/todo/save",postData); // response.EnsureSuccessStatusCode(); }#L3 at this line PostAsJsonAsync used for sending a serialized payload to the API endpoint.
#L4-L6 at these lines old implementation code commented.
Support Me!
Buy Me A Coffee
PayPal Me
Wrapping Up:
Hopefully, I think this article delivered some useful information about System.Net.Http.Json package of extension methods used for Httpclient. I love to have your feedback, suggestions, and better techniques in the comment section below.
This is something we need to do all the time, but I was not aware of this package. Thanks for sharing!
ReplyDelete