skip to Main Content

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

Answers


  1. 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.

    Login or Signup to reply.
  2. 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();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search