发布回复没有预期的数据

时间:2018-01-31 11:45:37

标签: c#

以下是我的一个控制器的简单操作方法:

[HttpPost]
public async Task<dynamic> UnitTest()
{
    var httpClient = new HttpClient();
    dynamic model1 = new ExpandoObject();
    model1.title = "foo";
    model1.body = "bar";
    model1.userId = 1;
    var request = JsonConvert.SerializeObject(model1);
    var url = "https://jsonplaceholder.typicode.com/posts";
    var response = await httpClient.PostAsync(url, 
        new StringContent(request, Encoding.UTF8, "application/json"));
    return response;
}

我希望response包含像

这样的对象
{
  id: 101,
  title: 'foo',
  body: 'bar',
  userId: 1
}

根据https://github.com/typicode/jsonplaceholder#how-to。相反,响应是具有以下属性的对象:

Content (empty)
StatusCode: 201
ReasonPhrase: "Created"
Version: 1.1

我做错了什么?

2 个答案:

答案 0 :(得分:1)

您只需要阅读内容,然后在传回之前将其反序列化为对象。

var str = await response.Content.ReadAsStringAsync();
var obj = JsonConvert.DeserializeObject(str);
return obj;

答案 1 :(得分:1)

response.Content是流内容,您应该在返回操作之前先读取流。

var content = await response.Content.ReadAsStringAsync();

完整行动看起来像;

[HttpPost]
public async Task<string> UnitTest()
{
    var httpClient = new HttpClient();
    dynamic model1 = new ExpandoObject();
    model1.title = "foo";
    model1.body = "bar";
    model1.userId = 1;
    var request = JsonConvert.SerializeObject(model1);
    var url = "https://jsonplaceholder.typicode.com/posts";
    var response = await httpClient.PostAsync(url, 
        new StringContent(request, Encoding.UTF8, "application/json"));
    var content = await response.Content.ReadAsStringAsync();
    return content;
}

此外,将返回的json反序列化为已知类型可能更好。