cty*_*cty 6 .net c# httpclient httpclienthandler
当使用 HttpClient 实例和 HttpClientHandler 实例(.Net Framework,不使用 Core)时,是否可以稍后以任何方式访问 HttpClientHandler 实例/它的属性(用于只读目的)?
不幸的是,创建 HttpClientHandler 实例作为变量供以后引用是不可能的,因为 HttpClient 实例作为参数传递给库,我们无法更改调用客户端。
例如,我想实现这样的目标:
// Created in client we cant modify
var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = True, PreAuthenticate = True });
// Class we can modify
public void DoSomething(HttpClient client)
{
if (client.HttpClientHandler.UseDefaultCredentials == True) Console.WriteLine("UseDefaultCredentials: True");
}
Run Code Online (Sandbox Code Playgroud)
dev*_*ron -1
让我重新编辑我的答案。使用构造函数
public class MyClass {
private readonly HttpClientHander _handler;
private readonly HttpClient _client;
public MyClass() {
_handler = new HttpClientHander() { /* Initialize the properties */ }
_client = new HttpClient(_handler);
}
public void MyMethod() {
if (_handler.TheProperty == true;) // Do something
}
}
Run Code Online (Sandbox Code Playgroud)
我希望这是有道理的。我确信它可以工作,因为对象的引用方式。