gpt4 book ai didi

c# - 如何从 ApiController 中的 StringContent 对象读取 JSON?

转载 作者:太空狗 更新时间:2023-10-29 20:23:09 26 4
gpt4 key购买 nike

我正在编写一个 API Controller ,用于接收和解析 JSON 异步帖子的内容,但无法读取该帖子中的 StringContent 对象的内容。

这是我的 API Controller 中我希望看到值的部分。到达 ApiController 方法的值为空。并且 jsonContent 值为空字符串。我期望看到的是 JSON 对象的内容。

public class ValuesController : ApiController
{
// POST api/values
public void Post([FromBody]string value)
{
HttpContent requestContent = Request.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;

// Also tried this per mybirthname's suggestion.
// But content ends up equaling 0 after this runs.
var content = Request.Content.ReadAsStreamAsync().Result.Seek(0, System.IO.SeekOrigin.Begin);
}
}

这是我的 Controller ,显示了它是如何被调用的。

[HttpPost]
public ActionResult ClientJsonPoster(MyComplexObject myObject)
{
this.ResponseInfo = new ResponseInfoModel();
PostToAPI(myObject, "http://localhost:60146", "api/values").Wait();
return View(this.ResponseInfo);
}

这是发帖方式。

private async Task PostToAPI(object myObject, string endpointUri, string endpointDirectory)
{
string myObjectAsJSON = System.Web.Helpers.Json.Encode(myObject);
StringContent stringContent = new StringContent(myObjectAsJSON, Encoding.UTF8, "application/json");
using (HttpClient httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(endpointUri);
using (HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(endpointDirectory, stringContent).ConfigureAwait(false))
{
// Do something
}
}
}

我怀疑 ApiController 中的 Post 方法的签名有问题。但不知道应该如何改变。感谢您的帮助。

最佳答案

您正在混合异步和同步调用,这将导致死锁。

将 Controller 更新为

[HttpPost]
public async Task<ActionResult> ClientJsonPoster(MyComplexObject myObject) {
this.ResponseInfo = new ResponseInfoModel();
await PostToAPI(myObject, "http://localhost:60146", "api/values");
return View(this.ResponseInfo);
}

还有 [FromBody]用于强制 Web API 从请求正文中读取简单类型。

更新API

public class ValuesController : ApiController {
// POST api/values
[HttpPost]
public async Task Post() {
var requestContent = Request.Content;
var jsonContent = await requestContent.ReadAsStringAsync();

}
}

关于c# - 如何从 ApiController 中的 StringContent 对象读取 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40407884/

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