C# HttpClient POST 请求处理响应

标签 c# dotnet-httpclient

我需要向接收参数用户名、密码和产品 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/

相关文章:

c# - 推荐的 ServiceStack API 结构

c# - 在集合中存储对公共(public)字段的引用

c# - 使用 REST 和 HTTPClient 在 SP2013 中创建文件夹

c# - 为什么用viewbag渲染数据会出错?

c# - 在 Windows Phone 项目中将值从一个页面传递到另一个页面

c# - 'volatile' 阻止 C# 中的编译器优化的示例?

c# - 如何在 ASP.NET Core 中测试 https 重定向?

c# - 如何在 C# 中的 HttpClient 中使用凭据?

c# - .NET C# : HttpClient and the TaskCanceledException exception

c# - HttpClient.PostAsync 挂起,直到所有 System.Timer 启动