我需要向接收参数用户名、密码和产品 ID 的 API 发出 POST 请求。我创建了该部分并且工作正常,但是当发送参数正确时,我该如何处理响应 API 返回状态 200 和产品目的。在其他情况下,当发送参数错误时,API 返回 200 和 json 对象,如下所示:
{
"Username": {
"Messages": [
"The Username field is required."
]
},
"Password": {
"Messages": [
"The Password field is required."
]
},
"ProductId": {
"Messages": [
"The productId field is required."
]
}
}
那么我该如何处理这样的事情。
这是我的 POST 请求代码:
public async Task<string> PostProductId(string path)
{
using (var client = GetHttpClient())
{
string content = null;
try
{
string endpoint = path;
string requestJson = JsonConvert.SerializeObject(bodyObject);
HttpContent httpContent = new StringContent(requestJson, Encoding.UTF8, "application/json");
var response = await client.PostAsync(endpoint, httpContent);
content = response.Content.ReadAsStringAsync();
}
catch (HttpRequestException ex)
{
Console.WriteLine("ERROR: " + ex.Message);
return null
}
return content;
}
}
最佳答案
要返回状态和对象,您可以使用 IHttpActionResult
。
你可以在不测试的情况下做这样的事情:
public async Task<IHttpActionResult> PostProductId(string path)
{
using (var client = GetHttpClient())
{
string content = null;
try
{
string endpoint = path;
string requestJson = JsonConvert.SerializeObject(bodyObject);
HttpContent httpContent = new StringContent(requestJson, Encoding.UTF8, "application/json");
var response = await client.PostAsync(endpoint, httpContent);
content = response.Content.ReadAsStringAsync();
}
catch (HttpRequestException ex)
{
Console.WriteLine("ERROR: " + ex.Message);
return InternalServerError(ex);
}
return Ok(content);
}
}
一些引用:
关于C# HttpClient POST 请求处理响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55632689/