6

Using .NET Core 3.1, I have the following Http client which builds a HTTP POST containing multipart/form-data body:

public async Task SendRequest(string randomString, IFormFileCollection files) 
{
    var form = new MultipartFormDataContent();
    
    form.Add(new StringContent(randomString), "randomString");
    
    foreach (var file in files)
    {
        var stream = new MemoryStream();
        await file.CopyToAsync(stream, cancellationToken);
        form.Add(new StreamContent(stream), "files");
    }

    using var request = new HttpRequestMessage(HttpMethod.Post, $"api/endpoint")
    {
        Content = form
    };

    await _httpClient.SendAsync(request);
}

The receiving controller looks like this:

[Consumes("multipart/form-data")]
[HttpPost]
public async Task ReceiveForm([FromForm] RequestModel request)
{
    //Do stuff
}

RequestModel looks like this:

public class RequestModel 
{
    [JsonPropertyName("randomString")]
    public string RandomString { get; set; }

    [JsonPropertyName("files")]
    public IFormFileCollection Files { get; set; }
}

The problem I am seeing is that requestModel.RandomString gets populated, but the requestModel.Files does not - it is null. What am I doing wrong?

1 Answer 1

4

thanks for the perfect code in example!

You should set both parameters (name and fileName) to files - form.Add(new StreamContent(stream), "files", "files");

Method description:

Parameters:
content: The HTTP content to add to the collection.
name: The name for the HTTP content to add.
fileName: The file name for the HTTP content to add to the collection.

This is my example:

var fileName = "files";
var byteArrayContent = new ByteArrayContent(fileBytes1);
form.Add(byteArrayContent, fileName, fileName);

var stream = new MemoryStream(fileBytes2);
form.Add(new StreamContent(stream), fileName, fileName);

Results: Results

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

2 Comments

Adding a file name worked! Thank you!
No problem :) Also thank you for a good example

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.