1

i am using HttpClient to send request, i want to use my custom request headers using HttpClient in GET Method?

Here is my code:

public HttpResponseMessage Get(string url, List<KeyValuePair<string, string>> headers = null)
    {
        HttpRequestMessage request = new HttpRequestMessage()
        {
            RequestUri = new Uri(url),
            Method = HttpMethod.Get,
        };
        if (headers != null && headers.Count > 0)
        {
            foreach (var header in headers)
            {                    
                request.Headers.Add(header.Key, header.Value);

            }
        }            
        HttpResponseMessage response = httpClient.SendAsync(request).Result;
        return response;
    }

But it threw an error at request.Headers.Add(header.Key, header.Value);

Below is the error message:

Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.

Any help would be appreciated

20
  • Did you debug the code? What values you have in header.Key and header.Value when you get the exception? Commented Jan 24, 2019 at 9:20
  • My header is "Content-Type" "application/json". I found the workaround at stackoverflow.com/questions/10679214/…, but it is only suitable for Http Post method Commented Jan 24, 2019 at 9:23
  • For GET request setting Content-Type header is not valid. You simply can not set Content-Type header for GET requests. You should not. Commented Jan 24, 2019 at 9:28
  • @LeeLiu that's not a workaround, that's the answer. GET has no content so using Content-Type is a bug. If you want to request a specific content type use the Accept header Commented Jan 24, 2019 at 9:29
  • @ChetanRanpariya If i want to set my customer header like "domain:005", how can i do that? Commented Jan 24, 2019 at 9:30

1 Answer 1

2

You should do this with using your HttpClient instance like below:

httpClient.DefaultRequestHeaders
      .Accept
      .Add(new MediaTypeWithQualityHeaderValue("x-your-custom-header"));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.