An open API service indexing awesome lists of open source software.

https://github.com/wilsonneto-dev/demo-httpclient-factory

A demo on how to use HttpClient factory (Named HttpClients, Typed HttpClients, IHttpClientFactory)
https://github.com/wilsonneto-dev/demo-httpclient-factory

dotnet dotnet-core httpclientfactory

Last synced: 12 months ago
JSON representation

A demo on how to use HttpClient factory (Named HttpClients, Typed HttpClients, IHttpClientFactory)

Awesome Lists containing this project

README

          

## IHttpClientFactory - Demo

This repo is an example of the best ways of using HttpClient and IHttpClientfactory.

Instantiating HttpClients directly in the components that will use it (not recommended):

```csharp

internal class OpenAiGateway(IOptions openAiSettings)
{
private readonly string _baseAddress = openAiSettings.Value.BaseAddress;
private readonly string _apiKey = openAiSettings.Value.ApiKey;

public async Task ExecutePrompt(string prompt)
{
var client = new HttpClient { BaseAddress = new (_baseAddress) };
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");

var httpResponse = await client.PostAsJsonAsync("chat/completions",
new CompletionsRequest("gpt-4o", [ new Message("user", prompt) ]));

var response = await httpResponse.Content.ReadFromJsonAsync();

return response!.Choices[0].Message.Content;
}
}

```

Instantiating HttpClients using factory, but it still in the components that will use it (not recommended):

```csharp

builder.Services.AddHttpClient();

// ...

internal class OpenAiGateway
{
private readonly HttpClient _httpClient;

public OpenAiGateway(IOptions openAiSettings, IHttpClientFactory httpClientFactory)
{
_httpClient = httpClientFactory.CreateClient();
_httpClient.BaseAddress = new (openAiSettings.Value.BaseAddress);
_httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {openAiSettings.Value.ApiKey}");
}

public async Task ExecutePrompt(string prompt)
{
var httpResponse = await _httpClient.PostAsJsonAsync("chat/completions",
new CompletionsRequest("gpt-4o", [ new Message("user", prompt) ]));

var response = await httpResponse.Content.ReadFromJsonAsync();

return response!.Choices[0].Message.Content;
}
}

```

Named HttpClients (recommended):

```csharp

// to add

```

Typed HttpClients (recommended):

```csharp

services.AddSingleton, OpenAiSettingsValidate>();
services.AddOptionsWithValidateOnStart()
.Bind(configuration);

services.AddTransient();

services.AddHttpClient((serviceProvider, httpClient) =>
{
var openAiSettings = serviceProvider.GetRequiredService>();
httpClient.BaseAddress = new (openAiSettings.Value.BaseAddress);
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {openAiSettings.Value.ApiKey}");
});

// ...

internal class OpenAiGateway(HttpClient httpClient)
{
public async Task ExecutePrompt(string prompt)
{
var httpResponse = await httpClient.PostAsJsonAsync("chat/completions",
new CompletionsRequest("gpt-4o", [ new Message("user", prompt) ]));

var response = await httpResponse.Content.ReadFromJsonAsync();

return response!.Choices[0].Message.Content;
}
}

```

Message handler example:

```csharp

services.AddHttpClient((serviceProvider, httpClient) =>
{
var openAiSettings = serviceProvider.GetRequiredService>();
httpClient.BaseAddress = new (openAiSettings.Value.BaseAddress);
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {openAiSettings.Value.ApiKey}");
})
.AddHttpMessageHandler();

// ...

public class LoggingHandler(ILogger logger) : DelegatingHandler
{
protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
logger.LogInformation("Request: {Body}", await request.Content!.ReadAsStringAsync());

var response = await base.SendAsync(request, cancellationToken);

logger.LogInformation("StatusCode: {StatusCode}", response.StatusCode);
var responseContent = await response.Content.ReadAsStringAsync();
logger.LogInformation("Content: {Content}", responseContent);

return response;
}
}

```

This demo uses:
- .Net 9

---

| [][1] |
| :-: |
|[Wilson Neto][1]|

[1]: https://github.com/wilsonneto-dev