Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register a Typed HttpClient in a ASP.NET Core 2.1 application

I'm trying to register a Typed HttpClient in my ASP.NET 2.1 Web Application where the Typed HttpClient requires an API Key, defined in the constructor.

e.g.

Startup.cs
----------
services.AddHttpClient<MyHttpClient>();


MyHttpClient.cs
---------------
public class MyHttpClient(string apiKey, HttpClient httpClient) { .. }

As you can see, I'm pretty sure the IoC/DI wouldn't know how to create the instance of the MyHttpClient because it wouldn't know what value to inject into the string apiKey parameter.

Is this possible?

I've also tried referencing the Microsoft docs about "Fundamentals - Http Requests (Typed Clients)" but couldn't see any examples of this.

like image 226
Pure.Krome Avatar asked Oct 22 '25 20:10

Pure.Krome


2 Answers

You can configure your api key in Startup when you register the typed client

services.AddHttpClient<MyHttpClient>(c => 
{ 
    c.DefaultRequestHeaders.Add("Authorization", "{apikey}"); 
});
like image 87
Brad Avatar answered Oct 25 '25 10:10

Brad


For named clients the answer of Brad may be the only solution. But for typed clients you can inject the key as suggested by mjwills.

In startup:

services.AddSingleton<IApiKeyProvider, ApiKeyProvider>();

Where ApiKeyProvider is:

public class ApiKeyProvider: IApiKeyProvider
{
    public string ApiKey { get; set; }
}

And inject into the typed client:

public class MyHttpClient
{
    public HttpClient Client { get; }

    public MyHttpClient(HttpClient client, IApiKeyProvider apiKeyProvider)
    {
        var key = apiKeyProvider.ApiKey;
    }
}

Or when the key is stored in the configuration then you can use IOptions.

In startup:

services.Configure<ApiSettings>(options => configuration.GetSection("ApiSettings").Bind(options));

Where ApiSettings is:

public class ApiSettings
{
    public string ApiKey { get; set; }
}

And inject into the typed client:

public class MyHttpClient
{
    public HttpClient Client { get; }

    public MyHttpClient(HttpClient client, IOptions<ApiSettings> apiSettings)
    {
        var key = apiSettings.Value.ApiKey;
    }
}

In the same way you can access the request context, like when you want to read the current access_token, as described in my answer here.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!