3 回答

TA貢獻(xiàn)1111條經(jīng)驗(yàn) 獲得超0個(gè)贊
在您的代碼中,獲取 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>
編輯:
要訪問屬性,請(qǐng)安裝 Newtonsoft.Json 包并嘗試以下代碼。
var jsonString = ...
JObject jo = JObject.Parse(jsonString);
Console.WriteLine(jo["access_token"]);

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超4個(gè)贊
要解決此問題,您可以執(zhí)行的操作之一是通過添加正確的請(qǐng)求標(biāo)頭來專門請(qǐng)求響應(yīng)中的 json 格式
Accept:?application/json
像這樣嘗試一下
client.DefaultRequestHeaders.Accept.Add(new?MediaTypeWithQualityHeaderValue("application/json"));
現(xiàn)在,如果服務(wù)器關(guān)注請(qǐng)求標(biāo)頭,它將返回一個(gè) json 給您。 它可能默認(rèn)為 xml,因?yàn)槟恼?qǐng)求中沒有此類標(biāo)頭,或者服務(wù)器僅支持返回 xml 響應(yīng)。
編輯:如果您無法讓服務(wù)器返回 json,您可以將 xml 字符串響應(yīng)轉(zhuǎn)換為 json 字符串。轉(zhuǎn)換后,您可以從控制器正常返回 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貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超3個(gè)贊
我認(rèn)為在這種情況下,FormUrlEncodedContent
是錯(cuò)誤的選擇,你應(yīng)該使用StringContent
,類似于:< /span>
var content = new StringContent(HttpUtility.UrlEncode(values), Encoding.UTF8, "application/json"); var response = await client.PostAsync("https://URL.com/Token", content);
原因是,我認(rèn)為 FormUrlEncodeContent 沒有重載來接受添加內(nèi)容類型。
另一種替代方法是改用 SendAsync 而不是 PostAsync,因?yàn)?SendAsync 具有一些額外的靈活性。
- 3 回答
- 0 關(guān)注
- 221 瀏覽
添加回答
舉報(bào)