.DisableAntiforgery() helps with error in topic, but catched another with binding IFormFile.. Then I took file from request manually and it’s worked:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
app.MapPost("/upload", async (HttpRequest request) => { if (!request.HasFormContentType || request.Form.Files.Count == 0) return Results.BadRequest("No file uploaded"); var file = request.Form.Files.FirstOrDefault(); if (file == null || file.Length == 0) return Results.BadRequest("File is empty"); // Happy return Results.Ok("TEST"); }) .DisableAntiforgery(); |
The best solution is:
Get the XSRF token before upload file; post token when upload.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Get token endpoint, call this and get token first 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 // Post files endpoint, attach the token with request 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:

Upload the file
Step 1: Get the token.

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.
