Search code examples
.netpostpostmanhttpclient

How to Send a Multipart/Form-Data POST Request with an Attachment in .NET?


I have a working Postman POST request where the body consists of one attachment file in application/json format, and the content type is multipart/form-data: enter image description here

However, I need to replicate the same request using .NET 7.
I've tried the following code, but it returns a 400 Bad Request in the httpResponse::

using var formDataContent = new MultipartFormDataContent();
using var content = JsonContent.Create(document); // document - it's an object
content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
formDataContent.Add(content);

var httpResponse = await _httpClient.PostAsync([my_url], content);

My goal is to send a multipart/form-data POST request with an attachment in application/json format, just like in Postman. What am I doing wrong, and how can I achieve this in .NET 7?


Solution

  • To make this query work, I specified the JsonContent name and fileName when adding it to MultipartFormDataContent:

    using var formDataContent = new MultipartFormDataContent();
    using var content = JsonContent.Create(document); // document - it's an object
    formDataContent.Add(content, "request", "request.json");