c# - 从 HttpClient 实例访问 HttpClientHandler?

标签 c# .net httpclient

当使用 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");
}

最佳答案

让我重新编辑我的答案。使用构造函数

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
  }
}
我希望这是有道理的。我确信它是有效的,因为对象的引用方式。

关于c# - 从 HttpClient 实例访问 HttpClientHandler?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62999782/

相关文章:

c# - Asp :net MVC 3: @Html. EditorFor 模板中模型的子集合?

c# - 限制跨 WCF 服务的请求数

angular - 响应主体为空,状态为 200

c# - 绘制长度超过 65536 的字符串时 GDI+ DrawString 通用异常?

c# - 在运行时动态创建函数

c# - 有没有办法在 XNA 中锁定 VertexBuffers?

c# - 表达式 `t => (t.SomeProperty As Object)` 指的是方法,而不是属性

c# - 在带有 .net 4.5 客户端的 Windows 7 上使用 WebSocket 的最佳方式

java - 如何为 apache commons httpclient 注册 url 处理程序

json - Bad Request -Post 方法 - JSON DateTime 问题