我知道我会因为问这个已经被问过一百万次的问题而被钉死在十字架上,我向你保证我已经看过其中的大部分问题/答案,但我仍然有点卡住。
这是一个支持 ASP.NET Core 6 API 的 .NET Standard 2.0 类库。
在我的文件中,Program.cs我创建了一个名为 HttpClient 的文件,如下所示:
builder.Services.AddHttpClient("XYZ_Api_Client", config =>
{
var url = "https://example.com/api";
config.BaseAddress = new Uri(url);
});
Run Code Online (Sandbox Code Playgroud)
我有一个将使用它的自定义客户端HttpClient,并且我创建了一个单例MyCustomClient,Program.cs以便我的存储库可以使用它。代码如下。这就是我陷入困境的地方,因为我不确定如何将我的名字传递HttpClient到MyCustomClient.
builder.Services.AddSingleton(new MyCustomClient(???)); // I think I need to pass the HttpClient to my CustomClient here but not sure how
Run Code Online (Sandbox Code Playgroud)
我CustomClient需要使用这个HttpClient命名XYZ_Api_Client来完成它的工作:
public class MyCustomClient
{
private readonly HttpClient _client;
public MyCustomClient(HttpClient client)
{
_client = …Run Code Online (Sandbox Code Playgroud) 我正在使用 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具有严格的行为,并且像前一个应用程序那样的代码会抛出异常,指出请求的命名客户端未定义?
c# .net-core asp.net-core asp.net-core-3.1 ihttpclientfactory