gpt4 book ai didi

c# - 如何使用 ASP.NET Core 依赖注入(inject)将 HttpMessageHandler 注入(inject)到 HttpClient 对象中?

转载 作者:太空宇宙 更新时间:2023-11-03 20:49:07 25 4
gpt4 key购买 nike

在不使用 ASP.NET Core 的 DI 的情况下,您可以使用其构造函数将包含 cookie 容器的 ClientHandler 放入 HttpClient 对象中,类似于以下内容:

        var cookieContainer = new CookieContainer();
var handler = new HttpClientHandler() { CookieContainer = cookieContainer };

var client = new HttpClient(handler)
{
BaseAddress = new Uri(uri),
Timeout = TimeSpan.FromMinutes(5)
};

但是当您尝试使用 DI 时,您没有机会调用 HttpClient 的构造函数并将处理程序传入。我尝试了下一行代码:

        services.AddHttpClient<HttpClient>(client =>
{
client.BaseAddress = new Uri(uri);
client.Timeout = TimeSpan.FromSeconds(5);
});

但实际上,当您获取实例时,它没有 cookie 容器。

最佳答案

您可以通过添加一个命名的客户端(它有额外的配置选项)来做到这一点。我们将简单地创建一个带有 cookie 容器的新 HttpClientHandler:

services.AddHttpClient("myServiceClient")
.ConfigureHttpClient(client =>
{
client.BaseAddress = new Uri(uri);
client.Timeout = TimeSpan.FromSeconds(5);
})
.ConfigurePrimaryHttpMessageHandler(
() => new HttpClientHandler() { CookieContainer = new CookieContainer() }
);

然后你可以像这样解析客户端:

public class MyService(IHttpClientFactory clientFactory)
{
// "myServiceClient" should probably be replaced in both places with a
// constant (const) string value to avoid magic strings
var httpClient = clientFactory.CreateClient("myServiceClient");
}

也可以通过向 AddHttpClient 提供通用参数将 HttpClient 绑定(bind)到服务:

services.AddHttpClient<MyService>("myServiceClient") // or services.AddHttpClient<MyServiceInterface, MyServiceImplementation>("myServiceClient")
.ConfigureHttpClient(client =>
{
client.BaseAddress = new Uri(uri);
client.Timeout = TimeSpan.FromSeconds(5);
})
.ConfigurePrimaryHttpMessageHandler(
() => new HttpClientHandler() { CookieContainer = new CookieContainer() }
);

然后您可以在您的服务中简单地接受一个HttpClient:

public class MyService
{
public MyService(HttpClient httpClient)
{
}
}

关于c# - 如何使用 ASP.NET Core 依赖注入(inject)将 HttpMessageHandler 注入(inject)到 HttpClient 对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57193111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com