我在StackOverflow上的第一篇文章,但我很长一段时间潜伏着!希望我能在我正在处理的问题上获得一些帮助。
我正在努力实现以下目标。下面的代码是将内容设置为JSON字符串,其中包含以下内容......
{
"access_token": "value1",
"expires_in": "value2",
"client_in": null,
"scope": "value3"
}
以下是将HttpResponseMessage发送回客户端的代码。
[HttpPost]
public HttpResponseMessage token(string grant_type,
string code,
string client_id,
string client_secret,
string redirect_uri)
{
WpOAuth2TokenRetValSuccessVM OA2_Success = new WpOAuth2TokenRetValSuccessVM();
OA2_Success.access_token = "value1";
OA2_Success.client_in = client_id;
OA2_Success.expires_in = "value2"; //...The number of seconds left in the lifetime of the token
OA2_Success.scope = "value3"; //...Each access token can have only 1 scope
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
string strJson = JsonConvert.SerializeObject(OA2_Success, Newtonsoft.Json.Formatting.Indented);
StringContent n = new StringContent(strJson, Encoding.UTF8, "application/json");
response.Content = n;
return response;
}
现在,在我的生活中客户端,我无法从内容中取回JSON字符串。这是我用来阅读内容的代码。
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>(str_KEY1, str_VALUE1));
postData.Add(new KeyValuePair<string, string>(str_KEY2, str_VALUE2));
postData.Add(new KeyValuePair<string, string>(str_KEY3, str_VALUE3));
postData.Add(new KeyValuePair<string, string>(str_KEY4, str_VALUE4));
postData.Add(new KeyValuePair<string, string>(str_KEY5, str_VALUE5));
HttpContent content = new FormUrlEncodedContent(postData);
httpClient.PostAsync(strURI, content).ContinueWith(requestTask =>
{
// Get HTTP response from completed task.
HttpResponseMessage response = requestTask.Result;
// Check that response was successful or throw exception
response.EnsureSuccessStatusCode();
// Read response asynchronously as string and write out
var responseValue = response.Content.ReadAsStringAsync();
responseValue.Wait();
string n = responseValue.Result;
var i = 0;
});
现在,字符串n的内容如下,但我如何获得JSON ??? 谢谢大家。
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StringContent, Headers:
{
Content-Type: application/json; charset=utf-8
}
答案 0 :(得分:0)
听起来很难解决问题,但应该注意的是,由于您使用的是Web API,因此无需自行序列化数据并构建HttpResponseMessage
;让框架为你做:
[HttpPost]
public WpOAuth2TokenRetValSuccessVM token(string grant_type,
string code,
string client_id,
string client_secret,
string redirect_uri)
{
return new WpOAuth2TokenRetValSuccessVM
{
access_token = "value1",
client_in = client_id,
expires_in = "value2",
scope = "value3"
};
}