Example repo to upload files to a Minimal API in .NET 8
.
I figured this out after going through this. As per the docs, to be able to upload files you need an Authorization header, a client certificate, or a cookie header.
To satisfy that requirement, I decided to pass Antiforgery token with the file upload POST request.
Now my API endpoints looks like this:
// Get token
app.MapGet("antiforgery/token", (IAntiforgery forgeryService, HttpContext context) =>
{
var tokens = forgeryService.GetAndStoreTokens(context);
var xsrfToken = tokens.RequestToken!;
return TypedResults.Content(xsrfToken, "text/plain");
});
//.RequireAuthorization(); // In a real world scenario, you'll only give this token to authorized users
// Add my file upload endpoint
app.MapPost("/upload_many", async (IFormFileCollection myFiles) =>
{
foreach (var file in myFiles)
{
// ...
}
return TypedResults.Ok("Ayo, I got your files!");
});
So I've got 2 endpoints now:
Step 1: Get the token from Postman.
Step 2.1: Before making the POST call to Upload endpoint, add the XSRF token you received from Step 1.
Step 2.2: Add the file you want to upload. pickle.png in my case.
Step 2.3: Hit send. At this point, you'll be able to make a successful call.