【问题标题】:Returning HttpResponseMessage from MVC HttpPost, with content of JSON从 MVC HttpPost 返回 HttpResponseMessage,内容为 JSON
【发布时间】:2014-05-09 09:29:10
【问题描述】:

我在 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
}

【问题讨论】:

  • 抱歉,您确定您发布的代码就是您正在运行的代码吗?你在做什么看起来不错。如果您在 HttpResponseMessage 上执行 ToString(),您将获得的输出。
  • 这里的服务器端代码是MVC?看起来更典型的 Web API。该代码可以显着减少,但这取决于您使用的框架。

标签: json asp.net-mvc-3 httpclient httpresponse


【解决方案1】:

听起来你发现了问题,但需要注意的是,由于你使用的是 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"
    };
}

【讨论】:

    猜你喜欢
    • 2013-11-26
    • 2014-11-16
    • 1970-01-01
    • 2016-10-24
    • 2020-06-18
    • 2011-05-03
    • 2022-12-30
    • 1970-01-01
    • 2016-11-25
    相关资源
    最近更新 更多