简体   繁体   中英

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 perfect: 在此处输入图像描述

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.

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM