IHttpClientFactory 和更改基础 HttpClient.BaseAddress

IHttpClientFactory and changing the base HttpClient.BaseAddress

IHttpClientFactory 和更改的最佳实践是什么 HttpClient.BaseAddress?

在创建我的依赖注入时,我是这样做的:

services.AddHttpClient("MyApp", c =>
    {
        c.BaseAddress = new Uri("https://myurl/");
        c.DefaultRequestHeaders.Add("Accept", "application/json");
    }).ConfigurePrimaryHttpMessageHandler(handler => new HttpClientHandler()
    { AutomaticDecompression = DecompressionMethods.GZip });

然后当我需要 HttpClient 时:

var client = clientFactory.CreateClient("MyApp");

这很好用,但有时 运行 BaseAddress 需要更改。在 运行 期间,我无法在注入后更改 BaseAddress。现在我可以完全忽略 BaseAddress 并只在 API 调用中发送整个地址,但是,我不知道这是否是正确的方法。像这样:

await using var stream = await client.GetStreamAsync($"{addresss}/{api}");
using var streamReader = new StreamReader(stream);
using var textReader = new JsonTextReader(streamReader);
var serializer = new JsonSerializer();
data = serializer.Deserialize<List<T>>(textReader);

there are times, during runtime that the BaseAddress needs to change. During the run I am not able to change the BaseAddress after it has been injected.

BaseAddress 可以更改直到第一个请求被发送。届时,它会被锁定,无法再次更改。 HttpClient 工厂模式假定每个注入的客户端只有一个 BaseAddress(可能未设置)。

Now I could ignore BaseAddress altogether and just send the entire address in the API call, however, I do not know if this is the correct way of doing it.

您的选择是:

  1. 定义多个客户端,每个客户端一个 BaseAddress。如果您有几个知名主机,这是正常方法。
  2. 定义单个客户端并且不使用 BaseAddress,在每次调用中传递整个 url。这是完全允许的。
  3. 定义您自己的工厂类型,使用 IHttpClientFactory 传递出 HttpClient 个实例,其中每个实例可以指定自己的 BaseAddress。如果您有一些代码需要一个BaseAddress(例如,Refit)但需要将其与动态主机一起使用,我只会使用这种更复杂的方法。