Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

c# - adding a handler to all clients created via IHttpClientFactory?

Is there a way to add a handler to all clients created by the IHttpClientFactory? I know you can do the following on named clients:

services.AddHttpClient("named", c =>
{
    c.BaseAddress = new Uri("TODO");
    c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    c.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue
    {
        NoCache = true,
        NoStore = true,
        MaxAge = new TimeSpan(0),
        MustRevalidate = true
    };
}).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
    AllowAutoRedirect = false,
    AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip
});

But I don't want to use named clients I just want to add a handler to all clients that are given back to me via:

clientFactory.CreateClient();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you use CreateClient with no parameters, you implicitly request a named client, where the name is Options.DefaultName (string.Empty). To affect this default instance, specify Options.DefaultName when calling AddHttpClient:

services.AddHttpClient(Options.DefaultName, c =>
{
    // ...
}).ConfigurePrimaryHttpMessageHandler(() =>
{
    // ...
});

Tobias J notes in the comments that the API docs for AddHttpClient states the following:

Use DefaultName as the name to configure the default client.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...