3/27/2023 0 Comments Http client factory![]() ![]() The documentation and how to call it is as follows:īased on the documentation and results provided as an example, we want to have a strongly typed output so I used json2csharp to convert JSON to C# but I made some changes to the result like the following: Suppose in our project we want to call the following address to get comprehensive information about the country we want. Install-Package Newtonsoft.Json -Version 12.0.3ĭotnet add package Newtonsoft.Json -version 12.0.3 Install-Package Refit.HttpClientFactory -Version 5.2.1ĭotnet add package Refit.HttpClientFactory -version 5.2.1 Refit is a library heavily inspired by Square's Retrofit library, and it turns your REST API into a live interface: This approach also makes unit testing easy while testing HttpClients as you no longer have to mock them. String result = await _gitHubClient.GetData() Public ValuesController( IGitHubClient gitHubClient) Private readonly IGitHubClient _gitHubClient Register this as a typed client using the following line. Return await _client.GetStringAsync( "/") Public class GitHubClient : IGitHubClient First, define a contract for the GitHubClient. Here, the HttpClient is exposed directly, but you can encapsulate the HttpClient entirely using the following way. There is another better way of making typed client work. ![]() Public ValuesController( GitHubClient gitHubClient) Private readonly GitHubClient _gitHubClient 1Īnd, use it in the following way in the API controller. You can register this as a typed client using the following line. ( "User-Agent", "HttpClientFactory-Sample") Public GitHubClient( HttpClient httpClient) Below is a custom class defined for Github client.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |