How to construct HttpClient POST Request with form-data in C#?

Viewed 3539

I am having issues constructing the POST request with form-data in C# using HTTPClient. i tried multiple approaches but nothing seems to work. Can you please help what I am missing?

Please be informed, the SWAGGER POST is working fine and based on that I am trying to construct the request.

The API parameters

rPath* string
(formData)
nName* string
(formData)
nFile string
(formData)
type* string
(formData)  
zFile file
file

The working swagger POST

curl -X POST "http://localhost:8888/server/api/v1.0/createfolder" -H "accept: text/plain; charset=UTF-8" -H "authorization: Basic XXXXXXX" -H "Content-Type: multipart/form-data" -F "rPath=/RootFolder/" -F "nName=testing" -F "type=Folder"

The Fiddler request header of the SWAGGER POST (This is working).

Fiddler Request details

    static void Main(string[] args)
    {
        var formData = new MultipartFormDataContent();
        HttpContent content = new FormUrlEncodedContent (new[]
        {
            new KeyValuePair<string, string>("rPath",  "/RootFolder/"),
            new KeyValuePair<string, string>("nName", "TestFolder"),
            new KeyValuePair<string, string>("type", "Folder")
        });           
        content.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");
        content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
         formData.Add(content);
        var url = "http://localhost:8888/server/api/v1.0/createfolder";
        HttpResponseMessage response = PostRoot(formData, url);
    }
    static HttpResponseMessage PostRoot(HttpContent content, string webMethod)
    {
        HttpResponseMessage response = new HttpResponseMessage();
        using (var client = new HttpClient() {  })
        {
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "xxxxxxx=");
            response = client.PostAsync(webMethod, content).Result;
        }

        return response;
    }
1 Answers
var client = new HttpClient();
var baseUrl = "https://someurl";
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "multipart/form-data");
var formContent = new MultipartFormDataContent
{
 {new StringContent("Value1"),"formparamname1"},
 {new StringContent("Value2"),"formparamname2" },
 {new StringContent("Value2"),"formparamname3"},
};
var response = client.PostAsync(baseUrl, formContent).Result;
response.EnsureSuccessStatusCode();
var result = string.Empty;
if (response.IsSuccessStatusCode)
 {
   result = response.Content.ReadAsStringAsync().Result;
 }
return result;
Related