Posting file stream and other parameters with form data in C#

34 views Asked by At

I am trying to call external POST API with form data and getting always 400 bad request error. The stream can be PDF or ZIP. In the following code the Stream type is System.IO.Stream.

using (MultipartFormDataContent formData = new MultipartFormDataContent())
{
    // Add file content
    formData.Add(new StringContent(summerymodel.author.fullName), "file.author.fullName");
    formData.Add(new StringContent(summerymodel.category.guid), "file.category.guid");
    formData.Add(new StringContent(string.IsNullOrWhiteSpace(summerymodel.description)?"": summerymodel.description), "file.description");
    formData.Add(new StringContent(summerymodel.edition + 1), "file.edition");
    formData.Add(new StringContent(summerymodel.format), "file.format");
    formData.Add(new StringContent("false"), "file.private");
    formData.Add(new StringContent("File"), "file.storageMethodName");
    formData.Add(new StringContent("Test-Title"), "file.title");
    formData.Add(new StreamContent(stream), "file.content", "TestFile.pdf");
    // Send POST request to the API
    HttpResponseMessage response = await client.PostAsync(editionUrl, formData);

    // Check if the response is successful
    if (response.IsSuccessStatusCode)
    {
        // Read response content as string
        string responseString = await response.Content.ReadAsStringAsync();
        Console.WriteLine("Response from API: " + responseString);
    }
    else
    {
        Console.WriteLine("API request failed with status code: " + response.StatusCode);
    }
}
0

There are 0 answers