如何从HttpClient的C#多在做时,你得到的响应体(How to get response b

2019-10-22 06:52发布

我试图使用后多System.Net.Http.HttpClient数据,所得到的响应是200 OK。

下面是我用的方法:

 public async Task postMultipart()
        {
            var client = new HttpClient();
            client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "multipart/form-data");


            // This is the postdata
            MultipartFormDataContent content = new MultipartFormDataContent( );
            content.Add(new StringContent("12", Encoding.UTF8), "userId");
            content.Add(new StringContent("78", Encoding.UTF8), "noOfAttendees");
            content.Add(new StringContent("chennai", Encoding.UTF8), "locationName");
            content.Add(new StringContent("32.56", Encoding.UTF8), "longitude");
            content.Add(new StringContent("32.56", Encoding.UTF8), "latitude");

            Console.Write(content);
            // upload the file sending the form info and ensure a result.
            // it will throw an exception if the service doesn't return a valid successful status code
            await client.PostAsync(fileUploadUrl, content)
                .ContinueWith((postTask) =>
                {
                    postTask.Result.EnsureSuccessStatusCode();
                });

        }
  • 如何从这种方法获得的响应主体?

Answer 1:

为了呼应乔恩(一个并不简单地与Jon不同意),不预异步/等待(混合异步/世界的await ContinueWith )的世界。

为了得到响应正文你需要一个第二等待下一个字符串:

var response = await client.PostAsync(fileUploadUrl, content);
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();


Answer 2:

提示:你打电话PostAsync ,并等待结果......但后来没有做任何事的。 目前尚不清楚为什么你使用ContinueWith或者,当你在一个异步的世界,可以只处理简单地说:

var response = await client.PostAsync(fileUploadUrl, content);
response.EnsureSuccessStatusCode();
// Now do anything else you want to with response,
// e.g. use its Content property


文章来源: How to get response body from httpclient c# when doing multipart