Search code examples
asp.net-core.net-coreasp.net-web-apiasp.net-core-webapi.net-5

Inject ILogger when registering HttpClient in Asp.Net Core 5.0


In Asp.Net Core when you register a custom service, like:

services.AddScoped<ISomeService, SomeService>();

Then, out of the box you can access the Microsoft ILogger from the contractor of SomeService class.

But if you register a custom HttpClient, like:

            services.AddHttpClient<ISomeHttpClient, SomeHttpClient>(client =>
            {
                client.BaseAddress = new Uri(Configuration["Url"]);
                client.DefaultRequestHeaders.Add("Accept", "application/json");
            });

Then, you cannot access the Microsoft ILogger from the constructor of SomeHttpClient. I get the error:

Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger'

I am aware that the framework is already logging HttpRequest activity for you. What I would like to do is to log the body of every single request in case the StatusCode is not successful.

Any ideas how to achieve this?


Solution

  • Can you use ILogger<SomeHttpClient> logger than using ILogger directly?

    Here is some code which does it and working properly.

    public class GitHubService
    {
        private readonly HttpClient _client;
        private readonly ILogger<GitHubService> _logger;
    
        public GitHubService(HttpClient client, ILogger<GitHubService> logger)
        {
            client.BaseAddress = new Uri("https://api.github.com/");
            // GitHub API versioning
            client.DefaultRequestHeaders.Add("Accept",
                "application/vnd.github.v3+json");
            // GitHub requires a user-agent
            client.DefaultRequestHeaders.Add("User-Agent",
                "HttpClientFactory-Sample");
    
            _client = client;
            _logger = logger;
        }
    
        public async Task<IEnumerable<string>> GetAspNetDocsIssues()
        {
            _logger.LogInformation("Getting issues from GitHub");
            return await _client.GetFromJsonAsync<IEnumerable<string>>(
                "/repos/aspnet/AspNetCore.Docs/issues?state=open&sort=created&direction=desc");
        }
    }
    

    Source code : https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-5.0