0

Is it possible too upload files from a DTO with asp.net minimal api's ?

I've tried this:

public class MyDto
{
    public string BlaBlaBla { get; set; }
    public List<ListOfUselessStuff> MyList { get; set; }
    public IFormFile MyFile { get; set; }
}

Endpoint

app.MapPost("MyRoute", DoStuff)
   .WithTags("Tags")
   .Accepts<MyDto>("multipart/form-data")
   .Produces<NewlyCreatedDto>(200)
   .ProducesValidationProblem(400)
   .ProducesProblem(401)
   .ProducesProblem(403)
   .RequireAuthorization(Policies.RequireAdmin);

And finally Do Stuff:

private async Task<IResult> CreateQuestion([FromServices]IMediator mediator, [FromForm] MyDto dto)
{
                    //do stuff
}

But I just manage too get:

"Expected a supported JSON media type but got "multipart/form-data; boundary=---------------------------29663231333811935594178759367"."

2 Answers2

1

This has been addressed with .NET 7. Support for IFormFile and IFormFileCollection has been added. You should be able to use it in your MediatR pipelines.

Ref: .NET 7 Minimal API Support for File Upload Bindings

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.MapPost("/upload", async (IFormFile file) =>
{
    var tempFile = Path.GetTempFileName();
    app.Logger.LogInformation(tempFile);
    using var stream = File.OpenWrite(tempFile);
    await file.CopyToAsync(stream);
});

app.MapPost("/upload_many", async (IFormFileCollection myFiles) =>
{
    foreach (var file in myFiles)
    {
        var tempFile = Path.GetTempFileName();
        app.Logger.LogInformation(tempFile);
        using var stream = File.OpenWrite(tempFile);
        await file.CopyToAsync(stream);
    }
});

app.Run();
akriy
  • 21
  • 2
  • Also to add more context, as of .NET 7, uploading a single file or multiple files is supported directly. But if you want to add form data in the body along with file(s), it is not supported. It _maybe_ supported in .NET 8 and is on the .NET 8 Backlog. Ref: [Minimal API Github 39430](https://github.com/dotnet/aspnetcore/issues/39430) – akriy Jan 29 '23 at 17:38
0

Currently there is no support for binding form forms but there will be in the future according to ASP.NET Core official documentation.

No support for binding from forms. This includes binding IFormFile. We plan to add support for IFormFile in the future.

https://learn.microsoft.com/en-us/aspnet/core/tutorials/min-web-api?view=aspnetcore-6.0&tabs=visual-studio#differences-between-minimal-apis-and-apis-with-controllers

What you can do is inject the HttpRequest and access the form property as in this solution https://stackoverflow.com/a/71499716/11618303.

Beny
  • 29
  • 1
  • 5