gpt4 book ai didi

c# - 帖子响应没有预期的数据

转载 作者:行者123 更新时间:2023-11-30 23:05:53 24 4
gpt4 key购买 nike

下面是我的一个 Controller 的简单操作方法:

[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 .相反,response 是一个具有以下属性的对象:

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

我做错了什么?

最佳答案

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

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

完成 Action 的样子;

[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 反序列化为已知类型。

关于c# - 帖子响应没有预期的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48541382/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com