Skip to content

Example repo to try file upload to a Minimal API in .NET 8

Notifications You must be signed in to change notification settings

akhanalcs/fileupload-minimal-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

fileupload-minimal-api

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:

Upload the file

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.

About

Example repo to try file upload to a Minimal API in .NET 8

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages