Skip to content

Instantly share code, notes, and snippets.

Last active May 11, 2023 00:02
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Http.HttpResults;
var builder = WebApplication.CreateBuilder();
var app = builder.Build();
string GetOrCreateFilePath(string fileName, string filesDirectory = "uploadFiles")
var directoryPath = Path.Combine(app.Environment.ContentRootPath, filesDirectory);
return Path.Combine(directoryPath, fileName);
async Task UploadFileWithName(IFormFile file, string fileSaveName)
var filePath = GetOrCreateFilePath(fileSaveName);
await using var fileStream = new FileStream(filePath, FileMode.Create);
await file.CopyToAsync(fileStream);
app.MapGet("/", (HttpContext context, IAntiforgery antiforgery) =>
var token = antiforgery.GetAndStoreTokens(context);
var html = $"""
<form action="/upload" method="POST" enctype="multipart/form-data">
<input name="{token.FormFieldName}" type="hidden" value="{token.RequestToken}" />
<input type="file" name="file" placeholder="Upload an image..." accept=".jpg, .jpeg, .png" />
<input type="submit" />
return Results.Content(html, "text/html");
app.MapPost("/upload", async Task<Results<Ok<string>, BadRequest<string>>> (IFormFile file, HttpContext context, IAntiforgery antiforgery) =>
await antiforgery.ValidateRequestAsync(context);
var fileSaveName = Guid.NewGuid().ToString("N") + Path.GetExtension(file.FileName);
await UploadFileWithName(file, fileSaveName);
return TypedResults.Ok("File uploaded successfully!");
catch (AntiforgeryValidationException e)
return TypedResults.BadRequest("Invalid anti-forgery token");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment