我必须使用httpclient在我的c#类中调用一个api。API需要content-type头部,我希望获得json形式的响应,所以我将content-type : application/json添加到postman中的头部,并执行post请求,它工作得很完美:
但是,如果我用内容类型编写其他代码,api将返回html代码。我必须做与C#中的邮递员完全相同的事情,下面是我的示例代码:
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();
但是结果总是HTML,而不是json。
发布于 2020-07-24 15:23:18
很有趣,但可以这样解决:
request.Content = new StringContent(myjson, Encoding.UTF8);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content.Headers.Add("No-Paging", "true");
https://stackoverflow.com/questions/63068504
复制相似问题