【问题标题】:C# HttpClient POST request handle responseC# HttpClient POST 请求句柄响应
【发布时间】: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


【解决方案1】:

要返回状态和对象,您可以使用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);
    }
}

一些参考:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-17
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    相关资源
    最近更新 更多