簡體   English   中英

c# HttpClient post response content-type application/json

[英]c# HttpClient post response content-type application/json

我必須使用 httpclient 在我的 c# class 中調用 api。 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: 在此處輸入圖像描述

但是,如果我在內容類型 api 中寫其他內容,則返回 html 代碼。 我必須做與 C# 中的 postman 完全相同的事情這是我的示例代碼:

            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。

有趣但以這種方式解決:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM