【发布时间】:2019-07-25 01:31:03
【问题描述】:
不使用 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 容器。
【问题讨论】:
-
OP 我更新了我的答案,因为有(可能)更好的方法。
标签: c# dependency-injection httpclient