0

I am writing code in C# to consume POST API that accepts form-body with the following parameters.

Files[Array] (User can send multiple files in request)

TemplateId[Int]

Also, I need to pass the bearer AuthToken as a header in the HTTP client Post Request.

I need some help writing the HTTP request with the above form data.

using (var client = new HttpClient())
{
   HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, $" {_apiBaseUri}/{route}");

   requestMessage.Headers.Authorization = new AuthenticationHeaderValue($"Bearer {authToken}");
   var pdfFiles = Directory.GetFiles($"C:\\files", "*.pdf");
   foreach (var filename in pdfFiles)
   {
      // create array[] of each File and add them to the form data request
   }
   // Add TemplateId in the form data request
} 

postman request enter image description here

swagger request enter image description here

2 Answers 2

1

you can add files with 'MultipartFormDataContent'.

private static async Task UploadSampleFile()
{
    var client = new HttpClient
    {
        BaseAddress = new("https://localhost:5001")
    };

    await using var stream = System.IO.File.OpenRead("./Test.txt");
    using var request = new HttpRequestMessage(HttpMethod.Post, "file");
    using var content = new MultipartFormDataContent
    {
        { new StreamContent(stream), "file", "Test.txt" }
    };

    request.Content = content;

    await client.SendAsync(request);
}

for more: https://brokul.dev/sending-files-and-additional-data-using-httpclient-in-net-core

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, Hamidreza. We also need to send the TemplateId field in the request. How can we add it to the same content?
you can add an object like new StringContent(JsonConvert.SerializeObject(request)); that in the request it has templateId with its value. then add that to your content.
0

The Below Code change worked for me,

using (var httpClient = new HttpClient())
{
    using (var request = new HttpRequestMessage(new HttpMethod("POST"), _apiBaseUri))
    {
        request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {authToken}");

        var pdfFiles = Directory.GetFiles($"C:\\test", "*.pdf");
        var multipartContent = new MultipartFormDataContent();
        multipartContent.Add(new StringContent("100"), "templateId");
        foreach (var filename in pdfFiles)
        {
            multipartContent.Add(new ByteArrayContent(File.ReadAllBytes(filename)), "files", Path.GetFileName(filename));
        }
        request.Content = multipartContent;

        var response = await httpClient.SendAsync(request);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.