3 回答

TA貢獻1111條經驗 獲得超0個贊
在您的代碼中,獲取 JSON 字符串后responseString,不要返回它,而是嘗試以下代碼。
...
string responseString = await response.Content.ReadAsStringAsync();
response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(responseString, Encoding.UTF8, "application/json");
return response;
您需要將方法返回值從 Task<Object> 更改為 Task<HttpResponseMessage>
編輯:
要訪問屬性,請安裝 Newtonsoft.Json 包并嘗試以下代碼。
var jsonString = ...
JObject jo = JObject.Parse(jsonString);
Console.WriteLine(jo["access_token"]);

TA貢獻1829條經驗 獲得超4個贊
要解決此問題,您可以執行的操作之一是通過添加正確的請求標頭來專門請求響應中的 json 格式
Accept:?application/json
像這樣嘗試一下
client.DefaultRequestHeaders.Accept.Add(new?MediaTypeWithQualityHeaderValue("application/json"));
現在,如果服務器關注請求標頭,它將返回一個 json 給您。 它可能默認為 xml,因為您的請求中沒有此類標頭,或者服務器僅支持返回 xml 響應。
編輯:如果您無法讓服務器返回 json,您可以將 xml 字符串響應轉換為 json 字符串。轉換后,您可以從控制器正常返回 json 字符串。
編輯:
好的,嘗試下面的示例:
var content = new FormUrlEncodedContent(new[]
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? new KeyValuePair<string, string>("client_id", ""),
? ? ? ? ? ? ? ? new KeyValuePair<string, string>("scope", ""),
? ? ? ? ? ? ? ? new KeyValuePair<string, string>("grant_type", "authorization_code"),
? ? ? ? ? ? ? ? new KeyValuePair<string, string>("redirect_uri", ""),
? ? ? ? ? ? ? ? new KeyValuePair<string, string>("code", ""),
? ? ? ? ? ? ? ? new KeyValuePair<string, string>("client_secret","")
? ? ? ? ? ? });
? ? ? ? ? ? AADTokenResponse TokenResponse = null;
? ? ? ? ? ? string _baseAddress = string.Format("https://yourTargetDomain.com/");
? ? ? ? ? ? using (var client = new HttpClient())
? ? ? ? ? ? {
? ? ? ? ? ? ? ? client.BaseAddress = new Uri(_baseAddress);
? ? ? ? ? ? ? ? client.DefaultRequestHeaders.Accept.Clear();
? ? ? ? ? ? ? ? client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
? ? ? ? ? ? ? ? var responseMessage = await client.PostAsync("targetApiSegment", content);
? ? ? ? ? ? ? ? if (responseMessage.IsSuccessStatusCode)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? var responseString = await responseMessage.Content.ReadAsStringAsync();
? ? ? ? ? ? ? ? ? ? TokenResponse = JsonConvert.DeserializeObject<AADTokenResponse>(responseString);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }

TA貢獻1836條經驗 獲得超3個贊
我認為在這種情況下,FormUrlEncodedContent
是錯誤的選擇,你應該使用StringContent
,類似于:< /span>
var content = new StringContent(HttpUtility.UrlEncode(values), Encoding.UTF8, "application/json"); var response = await client.PostAsync("https://URL.com/Token", content);
原因是,我認為 FormUrlEncodeContent 沒有重載來接受添加內容類型。
另一種替代方法是改用 SendAsync 而不是 PostAsync,因為 SendAsync 具有一些額外的靈活性。
- 3 回答
- 0 關注
- 229 瀏覽
添加回答
舉報