您好,登錄后才能下訂單哦!
怎么在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"); } }
看完上述內容,你們掌握怎么在HttpClient中添加默認請求報頭的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。