【发布时间】:2019-09-02 02:25:22
【问题描述】:
我需要向接收参数用户名、密码和 productId 的 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;
}
}
【问题讨论】:
-
定义“句柄”。是否要解析 JSON?
-
您说:“当发送参数错误时,API 返回 200”。那么你总是得到 200 响应并且没有例外吗?
-
它应该返回 BadRequest http 状态码 400。在这种情况下,尝试将这些属性添加到您的对象中,但如果响应的结构是 diff,则必须添加内容检查然后反序列化为对象或只需将 json 复制到字符串错误之类的属性?
-
如果您无法更改现有 API(即因为它是由第 3 方提供的)以返回实际的错误代码,您只需检查内容是否包含像您显示的“意外的东西”
-
你不应该是
usingHttpClient。而是使用 HttpClientFactory 创建新实例。参考:docs.microsoft.com/en-us/aspnet/core/fundamentals/…
标签: c# dotnet-httpclient