我正在尝试使用“ ConfigurePrimaryHttpMessageHandler”将处理程序附加到httpclientfactory
但是当我在HttpClient内部查看时 如果处理程序在那里,我找不到它
我正确附加了处理程序吗?
任何建议
services.AddHttpClient<IGitHubClient,GitHubClient>(client =>
{
client.BaseAddress = new Uri(myUri);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
})
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
AllowAutoRedirect = false,
AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip
});
public interface IGitHubClient
{
Task<string> GetData();
}
public class GitHubClient : IGitHubClient
{
private readonly HttpClient _client;
public GitHubClient(HttpClient httpClient)
{
_client = httpClient;
}
public async Task<string> GetData()
{
return await _client.GetStringAsync("/");
}
}
public class ValuesController : Controller
{
private readonly IGitHubClient _gitHubClient;;
public ValuesController(IGitHubClient gitHubClient)
{
_gitHubClient = gitHubClient;
}
[HttpGet]
public async Task<ActionResult> Get()
{
//my _gitHubClient has no Handler attached!!!
string result = await _gitHubClient.GetData();
return Ok(result);
}
}
答案 0 :(得分:2)
您显示的代码是推荐的方法。
关于_gitHubClient
的评论
//我的_gitHubClient没有附加的处理程序!!!
似乎是一种误解。
_gitHubClient
是将HttpClient
实例包装在其GitHubClient
实现中的抽象。
public class GitHubClient : IGitHubClient {
private readonly HttpClient _client; //<< Handler will be attached to this instance
public GitHubClient(HttpClient httpClient) {
_client = httpClient;
}
public async Task<string> GetData() {
return await _client.GetStringAsync("/");
}
}
包裹的实例将具有附加的处理程序。
根据当前配置,每当框架必须创建派生的IGitHubClient
的实例GitHubClient
进行注入时,工厂将使用启动时提供的设置来创建HttpClient
。其中还包括添加HttpClientHandler
提供的ConfigurePrimaryHttpMessageHandler