更新自定义标头值作为HttpClient的DefaultRequestHeaders添加

时间:2017-02-10 10:23:28

标签: c# asp.net-web-api httpclient

我在请求之间共享静态 httpclient ,我想为其添加一个自定义标头。

httpClient.DefaultRequestHeaders.Add("customHeader", somevalue.ToString());

但我注意到,在每个请求中,值都会添加到我打算在每个请求上替换的标头中。我尝试删除标题(如果它已经存在)并再次添加,但它在加载测试时出现错误。

if (httpClient.DefaultRequestHeaders.Contains("customHeader"))
        {
            httpClient.DefaultRequestHeaders.Remove("customHeader");
        }
httpClient.DefaultRequestHeaders.Add("customHeader",somevalue.ToString());

错误 -

System.ArgumentException: An item with the same key has already been added.
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
System.ArgumentNullException: Value cannot be null.

如何更新每个请求的自定义标头值?

3 个答案:

答案 0 :(得分:1)

我收到的错误:An item with the same key has already been added. Key: x

mahesh_ing回答的示例代码:

var request = new HttpRequestMessage
{
    Method = this.method,
    RequestUri = new Uri(this.requestUri),
};

request.Headers.Add("Key", "Value");

var client = new System.Net.Http.HttpClient
{
    Timeout = this.timeout
};

return await client.SendAsync(request);

答案 1 :(得分:1)

我在使用httpClient默认请求标头时遇到了同样的问题。参见下面的示例,而不是使用HttpRequestMessage.headers。

 _httpClient.DefaultRequestHeaders.Clear();
 _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));

        XDocument requestXml = JsonConvert.DeserializeXNode(message.ToString());

        HttpRequestMessage webRequest = new HttpRequestMessage()
        {
            Content = new StringContent(requestXml.Document.ToString().Replace("\r\n", string.Empty), Encoding.UTF8, "text/xml"),
            Method = HttpMethod.Post,
            RequestUri = new Uri(uri),
        };
        webRequest.Headers.Add("CorrelationId", correlationId);
        webRequest.Headers.Add("SOAPAction", endpointSOAPAction);

我以前使用默认请求标头进行我的相关操作和肥皂操作。

答案 2 :(得分:0)

我使用HttpRequestMessage向实际(当前)请求添加了标头,并用SendAsync而不是GetAsync替换了一个调用,它解决了我的问题。谢谢@levent。