From 9859e9d4aecfebf1ca97ad6fc3cae45d39f6e1e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florian=20J=C3=A4ckel?= Date: Wed, 24 Oct 2018 23:21:13 +0200 Subject: [PATCH] Check if the header exists and replace it rather than add it again (#299) --- SpotifyAPI.Web/SpotifyWebClient.cs | 32 +++++++++++++++--------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/SpotifyAPI.Web/SpotifyWebClient.cs b/SpotifyAPI.Web/SpotifyWebClient.cs index 7c3a572b..400400f0 100644 --- a/SpotifyAPI.Web/SpotifyWebClient.cs +++ b/SpotifyAPI.Web/SpotifyWebClient.cs @@ -39,10 +39,7 @@ namespace SpotifyAPI.Web { if (headers != null) { - foreach (KeyValuePair headerPair in headers) - { - _client.DefaultRequestHeaders.TryAddWithoutValidation(headerPair.Key, headerPair.Value); - } + AddHeaders(headers); } using (HttpResponseMessage response = Task.Run(() => _client.GetAsync(url)).Result) { @@ -58,10 +55,7 @@ namespace SpotifyAPI.Web { if (headers != null) { - foreach (KeyValuePair headerPair in headers) - { - _client.DefaultRequestHeaders.TryAddWithoutValidation(headerPair.Key, headerPair.Value); - } + AddHeaders(headers); } using (HttpResponseMessage response = await _client.GetAsync(url).ConfigureAwait(false)) { @@ -101,10 +95,7 @@ namespace SpotifyAPI.Web { if (headers != null) { - foreach (KeyValuePair headerPair in headers) - { - _client.DefaultRequestHeaders.TryAddWithoutValidation(headerPair.Key, headerPair.Value); - } + AddHeaders(headers); } HttpRequestMessage message = new HttpRequestMessage(new HttpMethod(method), url) @@ -125,10 +116,7 @@ namespace SpotifyAPI.Web { if (headers != null) { - foreach (KeyValuePair headerPair in headers) - { - _client.DefaultRequestHeaders.TryAddWithoutValidation(headerPair.Key, headerPair.Value); - } + AddHeaders(headers); } HttpRequestMessage message = new HttpRequestMessage(new HttpMethod(method), url) @@ -176,6 +164,18 @@ namespace SpotifyAPI.Web return newHeaders; } + private void AddHeaders(Dictionary headers) + { + foreach (KeyValuePair headerPair in headers) + { + if (_client.DefaultRequestHeaders.Contains(headerPair.Key)) + { + _client.DefaultRequestHeaders.Remove(headerPair.Key); + } + _client.DefaultRequestHeaders.TryAddWithoutValidation(headerPair.Key, headerPair.Value); + } + } + private static HttpClientHandler CreateClientHandler(ProxyConfig proxyConfig = null) { HttpClientHandler clientHandler = new HttpClientHandler