简体   繁体   English

C#HttpClient POST请求处理响应

[英]C# HttpClient POST request handle response

I need to make POST request to API which receives the parameters username, password, and productId.I created that part and it's working fine, but how can I handle response, when the send parameters are correct API returns status 200 and product object. 我需要向接收到参数用户名,密码和productId的API发出POST请求,我创建了该部件并且运行良好,但是当发送参数正确时,如何处理响应API返回状态200和产品对象。 In other case when send parameters are wrong API returns 200 and json object like bellow: 在其他情况下,当发送参数错误时,API将返回200和json对象(例如,波纹管):

{
    "Username": {
        "Messages": [
            "The Username field is required."
        ]
    },
    "Password": {
        "Messages": [
            "The Password field is required."
        ]
    },
    "ProductId": {
        "Messages": [
            "The productId field is required."
        ]
    }
}

so how can I handle somethnig like this. 所以我该如何处理这样的事情。

This is my code for POST request: 这是我的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;
    }
}

To return both status and object you can use IHttpActionResult . 要返回状态和对象,可以使用IHttpActionResult

You can do some thing like this with out testing it: 您可以在不进行测试的情况下执行以下操作:

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);
    }
}

Some Ref: 一些参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM