欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

为HttpClient添加默认请求报头的四种解决方案

程序员文章站 2022-09-06 23:34:28
前言 httpclient在web调用中具有广泛的应用,而为它添加默认请求头是我们经常遇到的需求,本文介绍4种为httpclient添加默认请求头的方式。下面话不多说了,...

前言

httpclient在web调用中具有广泛的应用,而为它添加默认请求头是我们经常遇到的需求,本文介绍4种为httpclient添加默认请求头的方式。下面话不多说了,来一起看看详细的介绍吧

第一种方式

直接在创建的httpclient对象的defaultrequestheaders集合中添加报头。

class program
{
  static task main()=> sendasync1();

  private static async task sendasync1()
  {
    var httpclient = new httpclient();
    adddefaultheaders(httpclient);
    await httpclient.getstringasync("http://localhost:5000/");
  }

  private static void adddefaultheaders(httpclient httpclient)
  {
    httpclient.defaultrequestheaders.add("x-www-foo", "123");
    httpclient.defaultrequestheaders.add("x-www-bar", "456");
    httpclient.defaultrequestheaders.add("x-www-baz", "789");
  }
}

第二种方式

对于.net core应用来说,我们更推荐的做法是采用依赖注入的方式,利用ihttpclientfactory来创建httpclient对象,那么我们在进行相关服务注册的时候就可以设置默认请求报头。

class program
{
  static task main()=> sendasync2();

  private static async task sendasync2()
  {
    var services = new servicecollection();
    services.addhttpclient("", adddefaultheaders);
    var httpclient = services
      .buildserviceprovider()
      .getrequiredservice<ihttpclientfactory>()
      .createclient();
    await httpclient.getstringasync("http://localhost:5000/");
  }

  private static void adddefaultheaders(httpclient httpclient)
  {
    httpclient.defaultrequestheaders.add("x-www-foo", "123");
    httpclient.defaultrequestheaders.add("x-www-bar", "456");
    httpclient.defaultrequestheaders.add("x-www-baz", "789");
  }
}

第三种方式

由于httpclient在发送请求的时候会利用diagnosticsource对象发送相应的诊断事件,并且将作为请求的httprequestmessage对象作为请求事件内容负载。我们可以订阅该事件,在请求被发送之前将其拦截下来,并添加相应的请求头即可。

class program
{
  static task main()=> sendasync3();

  private static async task sendasync3()
  {
    func<object, httprequestmessage> requestaccessor = null;
    diagnosticlistener.alllisteners.subscribe(listener =>
    {
      if (listener.name == "httphandlerdiagnosticlistener")
      {
        listener.subscribe(kv =>
        {
          if (kv.key == "system.net.http.httprequestout.start")
          {
            requestaccessor ??= buildrequestaccessor(kv.value.gettype());
            var request = requestaccessor(kv.value);
            adddefaultheaders(request);
          }
        });
      }
    });

    var httpclient = new httpclient();
    await httpclient.getstringasync("http://localhost:5000/");
    static func<object, httprequestmessage> buildrequestaccessor(type payloadtype)
    {
      var property = payloadtype.getproperty("request", bindingflags.instance | bindingflags.public);
      var payload = expression.parameter(typeof(object));
      var convertedpayload = expression.convert(payload, payloadtype);
      var getrequest = expression.call(convertedpayload, property.getmethod);
      var convert = expression.convert(getrequest, typeof(httprequestmessage));
      return expression.lambda<func<object, httprequestmessage>>(convert, payload).compile();
    }
  }

  private static void adddefaultheaders(httprequestmessage request)
  {
    request.headers.add("x-www-foo", "123");
    request.headers.add("x-www-bar", "456");
    request.headers.add("x-www-baz", "789");
  }
}

第四种方式

上面这种方式可以采用强类型编程方式,具体的代码如下。

class program
{
  static task main()=> sendasync4();

  private static async task sendasync4()
  {
    diagnosticlistener.alllisteners.subscribe(listener =>
    {
      if (listener.name == "httphandlerdiagnosticlistener")
      {
        listener.subscribewithadapter(new httpclientlistener());
      }
    });
      
    var httpclient = new httpclient();
    await httpclient.getstringasync("http://localhost:5000/");
  }

  private sealed class httpclientlistener
  {
    [diagnosticname("system.net.http.httprequestout.start")]
    public void onsend(httprequestmessage request) => adddefaultheaders(request);

    //must subscribute the system.net.http.httprequestout event.
    [diagnosticname("system.net.http.httprequestout")]
    public void onsend() { }
  }

  private static void adddefaultheaders(httprequestmessage request)
  {
    request.headers.add("x-www-foo", "123");
    request.headers.add("x-www-bar", "456");
    request.headers.add("x-www-baz", "789");
  }
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。