Author : HASSAN MD TAREQ

Http client in aspnet core

Json Serialization

To serialize

using System.Text.Json;
using System.Text.Json.Serialization;

var jsonStr = JsonSerializer.Serialize(MyObject)

To deserialize

var weatherForecast = JsonSerializer.Deserialize<MyObject>(jsonStr);

Using vanilla IHttpClientFactory and HttpClient

Typed client

RepoService.cs

public class RepoService
{
    private readonly HttpClient _httpClient;

    public RepoService(HttpClient client)
    {
        _httpClient = client;
    }

    public async Task<IEnumerable<string>> GetRepos()
    {
        var response = await _httpClient.GetAsync("aspnet/repos");

        response.EnsureSuccessStatusCode();

        using var responseStream = await response.Content.ReadAsStreamAsync(); // inline 'using' => C# 8.0+
        return await JsonSerializer.DeserializeAsync<IEnumerable<string>>(responseStream);
    }
}

Startup.ConfigureServices(...)

services.AddHttpClient<RepoService>(repoClient =>
{
    repoClient.BaseAddress = new Uri("https://api.github.com/");
    repoClient.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
    repoClient.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");
});

Usage

public class TypedClientModel : PageModel
{
    private readonly GitHubService _gitHubService;

    public TypedClientModel(GitHubService gitHubService)
    {
        _gitHubService = gitHubService;
    }

    public async Task OnGet()
    {
        try
        {
            var issues = await _gitHubService.GetAspNetDocsIssues();
        }
        catch(HttpRequestException)
        {
            // ... ... ...
        }
    }
}

See:

Flurl

Refit

Generating http client with NSwag