dotnet / dotnet/docs

Add documentation how to set up custom per request HttpMessageHandlers

Open
#24,286 1 comment 0 reactions 0 assignees View on GitHub
dotnet-architecture/svc microservices/subsvc
Dominant language
No language data
Stars
4.8k
Forks
6.1k
Avg merge
15h 21m
Merged PRs (30d)
370

Description

We have an endpoint that routes traffic to various endpoints that use different credentials and auth types (username/password combinations; basic and digest auth) based on the request parameters.

For now we have setup a factory class that instantiates a new HttpClient and HttpMessageHandler implementation for every request that is passing through. That does not seem right. We dispose the HttpClient in the consumer but is the HttpMessageHandler disposed correctly automatically?

Ideally we would leverage a pooled HttpMessageHandler approach such as is mentioned in this documentation. How can we add our own HttpMessageHandlers dynamically?

Also see the Stack Overflow question we have raised:
https://stackoverflow.com/questions/67588449/httpclient-pattern-with-dynamic-username-and-password

```c#
public class AuthenticatedHttpClientFactory : IAuthenticatedHttpClientFactory
{
public HttpClient GetClient(string username, string password)
{
var messageHandler = new HttpClientHandler()
{
Credentials = new NetworkCredential(username, password)
};
var client = new HttpClient(messageHandler);
return client;
}
}
```

---
#### Document Details

⚠ *Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.*

* ID: 7b506236-b211-eb9d-b571-5efecdde76c8
* Version Independent ID: 24434b0e-0b82-e477-9440-2cc8f135df75
* Content: [Use IHttpClientFactory to implement resilient HTTP requests](https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests)
* Content Source: [docs/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests.md](https://github.com/dotnet/docs/blob/main/docs/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests.md)
* Product: **dotnet-architecture**
* Technology: **microservices**
* GitHub Login: @nishanil
* Microsoft Alias: **nanil**

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.