当请求的命名客户端未定义时,使 ASP.NET core IHttpClientFactory 抛出异常

Enr*_*one 5 c# .net-core asp.net-core asp.net-core-3.1 ihttpclientfactory

我正在使用 ASP.NET core 3.1,并从 Visual Studio 2019 内置 ASP.NET core Web api 模板开始编写 Web api。

我的一项服务依赖于该IHttpClientFactory服务。我正在使用指定的客户端消费模式。所以,基本上,我有这样的代码:

var client = _httpClientFactory.CreateClient("my-client-name");
Run Code Online (Sandbox Code Playgroud)

我注意到,即使使用不存在的 HTTP 客户端的名称,前面的方法调用也能工作。我所说的不存在的 HTTP 客户端是指从未在方法内部定义的命名 HTTP 客户端Startup.ConfigureServices

换句话说,我希望下面的代码会抛出,但实际上它不会:

// code in Startup.ConfigureServices
services.AddHttpClient("my-client-name", c =>
{
  c.DefaultRequestHeaders.Add("User-Agent", "UserAgentValue");
});

// code in a custom service. I would expect this line of code to throw
var client = _httpClientFactory.CreateClient("not-existing-client");
Run Code Online (Sandbox Code Playgroud)

是否可以配置 ASP.NET core 3.1 应用程序,使其IHttpClientFactory具有严格的行为,并且像前一个应用程序那样的代码会抛出异常,指出请求的命名客户端未定义?

Nko*_*osi 3

是否可以配置 ASP.NET core 3.1 应用程序,以便 IHttpClientFactory 具有严格的行为,并且像前一个那样的代码会抛出异常,指出请求的命名客户端未定义?

基于源代码DefaultHttpClientFactory.Create

public HttpClient CreateClient(string name)
{
    if (name == null)
    {
        throw new ArgumentNullException(nameof(name));
    }

    HttpMessageHandler handler = CreateHandler(name);
    var client = new HttpClient(handler, disposeHandler: false);

    HttpClientFactoryOptions options = _optionsMonitor.Get(name);
    for (int i = 0; i < options.HttpClientActions.Count; i++)
    {
        options.HttpClientActions[i](client);
    }

    return client;
}

public HttpMessageHandler CreateHandler(string name)
{
    if (name == null)
    {
        throw new ArgumentNullException(nameof(name));
    }

    ActiveHandlerTrackingEntry entry = _activeHandlers.GetOrAdd(name, _entryFactory).Value;

    StartHandlerEntryTimer(entry);

    return entry.Handler;
}
Run Code Online (Sandbox Code Playgroud)

你所描述的是设计使然。如果客户端名称不存在,则只会为所使用的名称添加处理程序。