我正在尝试从API获得响应,但没有任何运气。我正在使用C#ASP.NET运行async
方法,但是来自response
的信息显示了状态和许多内容,但显示的是实际响应。
这是我的代码:
private static async Task PostBasicAsync(CancellationToken cancellationToken)
{
Michael Maik = new Michael();
Maik.name = "Michael";
Maik.id = "114060502";
Maik.number = "83290910";
string Url = "http://my-api.com/testing/give-your-data";
using (var client = new HttpClient())
using (var request = new HttpRequestMessage(HttpMethod.Post, Url))
{
var json = JsonConvert.SerializeObject(Maik);
using (var stringContent = new StringContent(
json,
Encoding.UTF8,
"application/json"))
{
request.Content = stringContent;
using (var response = await client
.SendAsync(request,
HttpCompletionOption.ResponseHeadersRead,
cancellationToken)
.ConfigureAwait(false))
{
response.EnsureSuccessStatusCode();
}
}
}
}
我的代码有什么问题? 它应该返回如下内容:
{
"message": "Hi Michael we have received your data succesfully!",
"data": {
"name": "Michael",
"id": "114060502",
"number": "83290910"
}
}
答案 0 :(得分:1)
通话response.EnsureSuccessStatusCode()
之后,您可以执行以下操作:
string resString = await response.Content.ReadAsStringAsync()
以获得实际的响应正文。