Search code examples
c#httppostasp.net-coremultipartform-data

How to post form-data IFormFile with HttpClient?


I have backend endpoint Task<ActionResult> Post(IFormFile csvFile) and I need to call this endpoint from HttpClient. Currently I am getting Unsupported media type error. Here is my code:

var filePath = Path.Combine("IntegrationTests", "file.csv");
var gg = File.ReadAllBytes(filePath);
var byteArrayContent = new ByteArrayContent(gg);
var postResponse = await _client.PostAsync("offers", new MultipartFormDataContent
{
    {byteArrayContent }
});

Solution

  • You need to specify parameter name in MultipartFormDataContent collection matching action parameter name (csvFile) and a random file name

    var multipartContent = new MultipartFormDataContent();
    multipartContent.Add(byteArrayContent, "csvFile", "filename");
    var postResponse = await _client.PostAsync("offers", multipartContent);
    

    or equivalent

    var postResponse = await _client.PostAsync("offers", new MultipartFormDataContent {
        { byteArrayContent, "csvFile", "filename" }
    });