[英]Access HttpClientHandler from HttpClient instance?
When working with a HttpClient instance and HttpClientHandler instance (.Net Framework, not using Core), is it possible to access the HttpClientHandler instance/its properties later in any way (for read-only purposes)?使用 HttpClient 实例和 HttpClientHandler 实例(.Net Framework,不使用 Core)时,是否可以稍后以任何方式访问 HttpClientHandler 实例/其属性(用于只读目的)?
Unfortunately creating the HttpClientHandler instance as a variable for referencing later isnt possible as the HttpClient instance is being passed to a library as a param and we cannot change calling client.不幸的是,创建 HttpClientHandler 实例作为稍后引用的变量是不可能的,因为 HttpClient 实例正在作为参数传递给库,我们无法更改调用客户端。
For example, I would like to achieve something like so:例如,我想实现这样的目标:
// 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");
}
Let me re-edit my answer.让我重新编辑我的答案。 Using the constructor使用构造函数
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
}
}
I hope this makes sense.我希望这是有道理的。 I'm sure it works because of the way objects are referrenced.由于引用对象的方式,我确信它可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.