2017-07-25 80 views
0

自從最近幾個月以來,我一直在隨機獲取此錯誤。我不知道什麼是重現這種具體的方式,但代碼多年沒有改變,而這個問題只是事發突然..C#HttpHeaders - 具有相同密鑰的項目已被添加

System.ArgumentException: An item with the same key has already been added. 
    at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) 
    at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) 
    at System.Net.Http.Headers.HttpHeaders.AddHeaderToStore(String name, HeaderStoreItemInfo info) 
    at System.Net.Http.Headers.HttpHeaders.CreateAndAddHeaderToStore(String name) 
    at System.Net.Http.Headers.HttpHeaders.GetOrCreateHeaderInfo(String name, Boolean parseRawValues) 
    at System.Net.Http.Headers.HttpHeaderValueCollection`1.SetSpecialValue() 
    at System.Net.Http.Headers.HttpGeneralHeaders.set_ConnectionClose(Nullable`1 value) 

所有我想要做的是ConnectionClose設爲true或null,像這樣:

_httpClient.DefaultRequestHeaders.ConnectionClose = _closingConnections; 

但是然後我得到關於已添加的相同的鍵的錯誤等。我該如何調試?

請指教。

謝謝!

+0

的價值在於它可能是你從多個線程在同一HttpClient的設置呢? – Bas

+1

似乎工作進程間歇性地將重複鍵值插入到請求頭字典中(顯示在堆棧跟蹤中)。如何在分配值之前檢查現有字典密鑰? –

+0

@Bas是的,它來自多個線程 –

回答

0
if (_client.DefaultRequestHeaders.Contains("ConnectionClose")) 
{ 
      _client.DefaultRequestHeaders.Remove("ConnectionClose"); 
} 
_client.DefaultRequestHeaders.ConnectionClose = _closingConnections 

試圖清理之前重新分配

+0

我設置_client.DefaultRequestHeaders從多個線程,這會有幫助嗎? –

相關問題