首页 > 解决方案 > 在 Http 响应消息中查找 POST 的结果

问题描述

我正在使用 VS2017 中的 Windows 窗体应用程序构建 REST 客户端(c#)。我已经能够使用 HttpClient.PostAsJsonAsync() 和 ReadAsync() 方法成功地从服务器获取和发布请求。我正在尝试将一些数据发布到服务器,并且在成功 POST 后,服务器会响应一个唯一的字符串,例如“1c77ad2e-54e0-4187-aa9d-9a55286b1f7a”

我得到了 POST 的成功响应代码(200 - OK)。但是,我不确定在哪里检查结果字符串。我检查了 HttpResponseMessage.Content 的内容

static async Task<HttpStatusCode> PostBurstData(string path, BurstRequest 
burstRequest)
    {
        HttpResponseMessage response = await client.PostAsJsonAsync(path, burstRequest);

        response.EnsureSuccessStatusCode();
        Console.WriteLine(response.Content.ToString());

        // return response
        return response.StatusCode;
    }

发送到该函数调用的数据如下:

BurstRequest request = new BurstRequest();
            request.NodeSerialNumbers = SubSerialList;
            request.StartTime = ((DateTimeOffset)dateTimePicker1.Value).ToUnixTimeMilliseconds();

            HttpStatusCode statusCode = new HttpStatusCode();

            statusCode = await PostBurstData(post_burst_url, request);

我应该在哪里搜索服务器响应成功 POST 的字符串?是否应该使用 ReadAsync() 读取内容?

if (response.IsSuccessStatusCode)
        {
            var data = await response.Content.ReadAsAsync();

        } 

标签: c#resthttpresponse

解决方案


为什么不尝试HttpContent如下使用:

using (HttpResponseMessage response = await client.GetAsync(url)) // here you can use your own implementation i.e PostAsJsonAsync
        {
            using (HttpContent content = response.Content)
            {
                string responseFromServer = await content.ReadAsStringAsync();

            }

        }

推荐阅读