【问题标题】:c# HttpClient post response content-type application/jsonc# HttpClient post response content-type application/json
【发布时间】:2020-11-14 00:29:38
【问题描述】:

我必须在我的 c# 类中使用 httpclient 调用一个 api。 API需要内容类型标头,我想以json形式获得响应,因此我将 content-type : application/json 添加到邮递员的标头并执行发布请求,并且效果很好:

但是,如果我在内容类型 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。

【问题讨论】:

  • 请不要打我:s ...您看到的HTML页面是错误页面吗?

标签: c# api httpclient


【解决方案1】:

有趣但这样解决了:

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

【讨论】: