Skip to content

IFormFileCollection minimal api behave different from mvc controller #49437

Closed
@kzhui125

Description

@kzhui125

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

I can get files with minimal api.
I can't get files with mvc controller.

Expected Behavior

No response

Steps To Reproduce

MapPost:

app.MapPost("/MinimalApi/Upload", async (IFormFileCollection files) =>
{
    await Task.CompletedTask;
    return Results.Ok(files.Count);
});

MapController:

[ApiController]
[Route("api/[controller]")]
public class TestController : ControllerBase
{
    // /Test/Upload
    [HttpPost("Upload")]
    public async Task<IActionResult> Upload([FromForm] IFormFileCollection files)
    {
        await Task.CompletedTask;
        return Ok(files.Count);
    }
}

Call await UploadAsync(urlMinimalApi) and await UploadAsync(urlMvcController)

the responseContent of MinimalApi is 2 (expected).
the responseContent of MvcController is 0 (unexpected).

private async Task UploadAsync(string url)
{
    using HttpClient httpClient = new();

    var content = new MultipartFormDataContent();

    using var stream1 = new MemoryStream("Content1"u8.ToArray());
    var fileContent1 = new StreamContent(stream1);
    fileContent1.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
    content.Add(fileContent1, "File1", "File1.txt");

    using var stream2 = new MemoryStream("Content2"u8.ToArray());
    var fileContent2 = new StreamContent(stream2);
    fileContent2.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
    content.Add(fileContent2, "File2", "File2.txt");

    var response = await httpClient.PostAsync(url, content);
    response.EnsureSuccessStatusCode();

    string responseContent = await response.Content.ReadAsStringAsync();

    Console.WriteLine(responseContent);
}

Exceptions (if any)

No response

.NET Version

7.0.304

Anything else?

What's wrong with my code? Or there is a bug in http client?

Thanks for your help.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-minimalIncludes minimal APIs, endpoint filters, parameter binding, request delegate generator etc

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions