0

I created a document using the IText library and I want to send this document in a post request to my other API. I tried to turn the document into an array of bytes but was unsuccessful and I got the following error: HTTP 415 Unsupported Media Type. How can I send and receive this document?

How I am sending:

var url = @"https://localhost:7253/User/Test";
            var httpClient = new HttpClient();

            using (MemoryStream ms = new MemoryStream())
            {
                PdfWriter writer = new PdfWriter(ms);
                PdfDocument pdf = new PdfDocument(writer);
                MultipartFormDataContent form = new MultipartFormDataContent();
                Document document = new Document(pdf);

                Paragraph p = new Paragraph("Hello World!")
                    .SetTextAlignment(TextAlignment.CENTER)
                    .SetFontSize(24);

                document.Add(p);

                document.Close();

                byte[] pdfBytes = ms.ToArray();
                ByteArrayContent content = new ByteArrayContent(pdfBytes);

                content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
                form.Add(content, "pdf", "documento.pdf");

                HttpResponseMessage response = await httpClient.PostAsync(url, form);
                if (response.IsSuccessStatusCode)
                {

                }
            }

How I'm getting:

[HttpPost("Teste")]
public IActionResult Post([FromBody] byte[] pdfBytes)
{
    Document document = ByteArrayToDocument(pdfBytes);

    return Ok();
}
guirms
  • 49
  • 7
  • try with this post https://stackoverflow.com/questions/4083702/posting-a-file-and-associated-data-to-a-restful-webservice-preferably-as-json – Paolino L Angeletti Mar 09 '23 at 14:58
  • Does the API accept an array of bytes? What is the `Content-Type` that it asks for? – Josh Heaps Mar 09 '23 at 16:01
  • The sending side wraps the PDF in `MultipartFormData` while the receiving side assumes that the request body is the PDF and only the PDF (no form wrapper). This doesn't match. – mkl Mar 09 '23 at 18:24

0 Answers0