Halit Kalayci
Halit Kalayci

Reputation: 129

C# HttpClient post response content-type application/json

I have to call an API in my C# class with httpclient. API need the content-type header, I want to get the response as JSON so I add content-type: application/json to headers in Postman and do the post request and it works perfectly:

enter image description here

But if I write something else in content-type API returns html code. I have to do the exactly same thing as Postman in C#. Here is my example code:

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("adress");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "adress");
request.Content = new StringContent(myjson, Encoding.UTF8, "application/json");
var y = await client.SendAsync(request);
var x = await y.Content.ReadAsStringAsync();

But the result is always HTML not JSON.

Upvotes: 1

Views: 3838

Answers (1)

Halit Kalayci
Halit Kalayci

Reputation: 129

Interesting but solved in this way :

request.Content = new StringContent(myjson, Encoding.UTF8);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content.Headers.Add("No-Paging", "true");

Upvotes: 3

Related Questions