我有一个使用 HttpClient 的控制台应用程序发出网络请求。
var client = new HttpClient();
我正在尝试添加多个 HttpMessageHandler到它( DelegatingHandler 的自定义实现,真的)但是 constructor for HttpClient只需要一个 HttpMessageHandler .
class LoggingHandler : DelegatingHandler { //... }
class ResponseContentProcessingHandler : DelegatingHandler { //... }
这没关系...
var client = new HttpClient(new LoggingHandler()); // OK
但这不能编译:
var client = new HttpClient(
new LoggingHandler(),
new ResponseContentProcessingHandler()); // Sadness
因为我的目标是 .NET 4.0,所以我不能使用 HttpClientFactory ,这就是通常解释此问题的解决方案的方式:
HttpClient client = HttpClientFactory.Create(
new LoggingHandler(),
new ResponseContentProcessingHandler());
因为我只是在控制台应用程序中,而不是在 ASP.NET 应用程序中,所以我也不能这样做:
GlobalConfiguration.Configuration
.MessageHandlers
.Add(new LoggingHandler()
.Add(new ResponseContentProcessingHandler());
我看过 source for HttpClientFactory并且似乎没有任何东西不能在 .NET 4.0 中编译,但是除了滚动我自己的工厂(“受微软源代码的启发”)之外,有没有办法手动添加许多 HTTP 消息处理程序到HttpClient ?
最佳答案
DelegatingHandler 有一个 protected constructor that takes a handler对于内部处理程序。如果您可以控制所有自定义处理程序,我认为您可以添加一个调用 protected 构造函数的公共(public)构造函数,例如:
public class CustomHandler : DelegatingHandler
{
public CustomHandler(HttpMessageHandler innerHandler) : base(innerHandler)
{
}
}
然后将它们链接起来:
var client = new HttpClient(
new CustomHandler(
new OtherCustomerHandler(
new HttpClientHandler()
)
)
);
关于c# - 如何在没有 HttpClientFactory 的情况下将多个 HttpMessageHandler 添加到 HttpClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36066722/