1. 程式人生 > >四種為HttpClient新增預設請求報頭的解決方案

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