1

Getting following error while adding header to HTTP Client:

{"ClassName":"System.IndexOutOfRangeException","Message":"Index was outside the bounds of the array.","Data":null,"InnerException":null,"HelpURL":null,"StackTraceString":"   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)\r\n   at System.Net.Http.Headers.HttpHeaders.AddHeaderToStore(String name, HeaderStoreItemInfo info)\r\n   at System.Net.Http.Headers.HttpHeaders.Add(String name, String value)

Following is the code how I am adding headers:

        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Add("api_key", _apiKey);
        client.DefaultRequestHeaders.Add("targetApp", "query");
        client.DefaultRequestHeaders.Add("accept", "application/x-www-form-urlencoded");
        client.DefaultRequestHeaders.Add("Application", _applicationName);
        client.DefaultRequestHeaders.Add("TraceId", traceId.ToString());

This is an intermitter issue, to fix this we have to restart IIS, after this code work fine.

Thanks a lot for helping in advance

7
  • Is any other code accessing the default headers at the same time against this client instance? traceId in particular doesn't look much like a "default" header unless that client is tightly scoped. In other words: is this client instance reused by anything concurrent? Commented Feb 9, 2023 at 7:24
  • Yes, we are reusing on concurrent calls
    – Dhrup
    Commented Feb 9, 2023 at 7:43
  • We have a API client where we make rest calls, this code is written inside API Client. in asp.net framework we were creating http client instance on each request but our team suggested that we should not create client request on each request
    – Dhrup
    Commented Feb 9, 2023 at 7:46
  • 1
    "we are reusing on concurrent calls" well that's the problem, then; you should only configure the default headers once, while they're not is use; if multiple clients are manipulating them, then: chaos. The default headers should only be the shared values that don't change per request; per-request headers can be set separately Commented Feb 9, 2023 at 14:51
  • 1
    reusing httpclient is strongly recommended; the problem is that you can't constantly be changing the default headers; use per-request headers for things that are per-request Commented Feb 10, 2023 at 11:45

1 Answer 1

0

I created HTTP client as a single object and then set the default header at once and changed the logic to set changing header at request level:

Custom header to HttpClient request

I implemented suggestion made by @Marc Gravell, and it is working well, no issues in past 15 days. Thanks a lot @Marc Gravell

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.