Wednesday, October 11, 2023

.NET 8 RC 2: IFormFile Support in [FromForm] in ASP.NET Core Minimal APIs

.NET 8 RC 2 was released today and we are just one month away from GA release. 

With this release, in ASP.NET Core Minimal APIs, we can now pass IFormFile or IFormFileCollection when we are posting form fields that are getting bound via [FromFormattribute.

Let's have a look at the following example where we are uploading a Single file.
using Microsoft.AspNetCore.Mvc;

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
// TODO: Add services to the builder

WebApplication app = builder.Build();
// TODO: Add middleware to the app

app.MapPost("/upload", ([FromFormFileUploadModel model) =>
{
    return Results.Ok();
})
.DisableAntiforgery();

app.Run();

internal record FileUploadModel(stringDescriptionIFormFile File);
And we can call the endpoint as follows.
curl--location 'https://localhost:5001/upload' \
--form 'description="Single File Upload"' \
--form 'file=@"/C:/Users/Jaliya/Desktop/Image1.jpg"'
And I can see the file getting bound.
IFormFile
If we want to upload multiple files, I can bind the endpoint to the following model.
internal record FilesUploadModel(stringDescriptionIFormFileCollection Files);
We can call the endpoint as follows.
curl--location 'https://localhost:7208/upload' \
--form 'description="Multiple File Upload"' \
--form 'files=@"/C:/Users/Jaliya/Desktop/Image1.jpg"' \
--form 'files=@"/C:/Users/Jaliya/Desktop/Image2.png"'
And now both the files are getting bound.
IFormFileCollection
Hope this helps.

Do try .NET 8 RC 2.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment