How to get response body from httpclient c# when doing multipart

痴心易碎 提交于 2019-12-11 05:36:55

问题


I am trying to post multipart data using System.Net.Http.HttpClient, the obtained response is 200 ok.

Here is the Method I used:

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

        }
  • How to obtain the response body from this method?

回答1:


To echo Jon (one does not simply disagree with Jon), do not mix the async/await world with the pre-async/await (ContinueWith) world.

To get the response body as a string you need a 2nd await:

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



回答2:


Hint: you're calling PostAsync, and awaiting the result... but then not doing anything with it. It's not clear why you're using ContinueWith either, when you're in an async world and can just handle it simply:

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


来源:https://stackoverflow.com/questions/29078917/how-to-get-response-body-from-httpclient-c-sharp-when-doing-multipart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!