简体   繁体   中英

Get HTTP response message from JSON POST method in C#

I am trying to get the response from an API but I am not getting any luck. I am running a async method using C# ASP.NET, but the info which comes from the response displays status and many things but the real response.

This is my code:

private static async Task PostBasicAsync(CancellationToken cancellationToken)
    {
        Michael Maik = new Michael();
        Maik.name = "Michael";
        Maik.id = "114060502";
        Maik.number = "83290910";
        string Url = "http://my-api.com/testing/give-your-data";
        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage(HttpMethod.Post, Url))
        {
            var json = JsonConvert.SerializeObject(Maik);
            using (var stringContent = new StringContent(
                                            json, 
                                            Encoding.UTF8, 
                                            "application/json"))
            {
                request.Content = stringContent;

                using (var response = await client
                    .SendAsync(request, 
                            HttpCompletionOption.ResponseHeadersRead,
                            cancellationToken)
                    .ConfigureAwait(false))
                {
                    response.EnsureSuccessStatusCode();
                }
            }
        }
    }

What is wrong with my code? It should return something like:

{
    "message": "Hi Michael we have received your data succesfully!",
    "data": {
        "name": "Michael",
        "id": "114060502",
        "number": "83290910"
    }
}

在调用response.EnsureSuccessStatusCode()之后,您可以执行以下操作: string resString = await response.Content.ReadAsStringAsync()以获取实际的响应主体。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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