HttpClient DefaultRequestHeaders.Add to Misused header name

Asked 2 years ago, Updated 2 years ago, 51 views

https://dev.projectoxford.ai/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f3039523b

I have created a process to use the Face API with reference to

of this Code samples
// Request headers
client.DefaultRequestHeaders.Add("Content-Type", "application/json");
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "{subscription key}";


in the section
{"Missed header name.Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.}
The exception is

Is the code of the sample wrong?Or are there other factors?

c#

2022-09-30 17:34

1 Answers

The HttpClient is configured differently for each meaning of the header.This is because it does not cause conflicts such as Content-Type headers when not POST.

// Request body
byte[] byteData=Encoding.UTF8.GetBytes("{body}");

using(var content=newByteArrayContent(byteData))
{
   content.Headers.ContentType = new MediaTypeHeaderValue("<your content type, i.e.application/json>");
   response=wait client.PostAsync(uri, content);
}

The part of is

using(var content=new StringContent("{body}", Encoding.UTF8, "application/json"))
    response=wait client.PostAsync(uri, content);

You can set the Content-Type header for the request body by writing .


2022-09-30 17:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.