C#HttpClient POST请求处理响应

时间:2019-04-11 12:35:59

标签: c# dotnet-httpclient

我需要向接收到参数用户名,密码和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;
    }
}

1 个答案:

答案 0 :(得分:0)

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

部分参考