skip to Main Content

I cannot add Content-type as "application/x-www-form-urlencoded". There is throwing an error. Only for the this content-type. Thank You for the attention.

using (var httpClient = new HttpClient())
{
    var request = new HttpRequestMessage
    {
        Method = new HttpMethod("POST"),
        RequestUri = new Uri(path),
    }; 

    request.Headers.Add("Accept", "application/json");
    request.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

    HttpResponseMessage response1 = await httpClient.SendAsync(request);
    var token = await response1.Content.ReadAsStringAsync();
}

It’s throwing error like that

"Misused header name, ‘Content-Type’. Make sure request headers are
used with HttpRequestMessage, response headers with
HttpResponseMessage, and content headers with HttpContent objects."

2

Answers


  1. The content type is a header of the content, not of the request, which is why this is failing.

    One way is that you can call TryAddWithoutValidation instead of add like below:

    request.Headers.TryAddWithoutValidation("Accept", "application/json");
    request.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
    

    The other way is that you can set the Content-Type when creating the request content itself, refer to this answer.

    Login or Signup to reply.
  2. I’v used something more complicated but it works.

            var client = new HttpClient();
            //headers dictionary
            var dict = new Dictionary<string, string>();
            dict.Add("Content-Type", "application/x-www-form-urlencoded");
            //request
            var req = new HttpRequestMessage(HttpMethod.Post, new Uri(url)) { Content = new FormUrlEncodedContent(dict) };
            req.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencode"));
            var response = await client.SendAsync(req);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search