Four solutions for adding default request headers to httpclient

Time:2020-5-30

preface

Httpclient has a wide range of applications in Web calls, and adding a default request header for it is a common requirement. This paper introduces four ways to add a default request header for httpclient. Let’s have a look at the detailed introduction

The first way

Add headers directly to the defaultrequestheaders collection of the created httpclient object.


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

The second way

For. Net core applications, we recommend using dependency injection to create httpclient objects with ihttpclientfactory. Then we can set the default request header when registering related services.


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

The third way

When httpclient sends the request, it will use the diagnosticsource object to send the corresponding diagnostic event, and use the httprequestmessage object as the request event content payload. We can subscribe to the event, intercept the request before it is sent, and add the corresponding request header.


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

The fourth way

The above method can adopt strong type programming, and the specific code is as follows.


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

summary

The above is the whole content of this article. I hope that the content of this article has some reference learning value for your study or work. Thank you for your support for developepaer.