ASP.NET Core and 404 not-found on static files
How to resolve if your ASP.NET Core application is throwing 404 not found on static files?
ASP.NET / .NET 8 / .NET 9 Freehosting
If you don't already have our ASP.NET / .NET Core Freehosting, sign up for FREE at https://MonsterASP.net/.
Description
You're building ASP.NET Core application and want to allow users upload static files (e.g. images, PDFs, documents etc.). Uploading working properly, file is uploaded to website content diretory however when trying to download or access it via URL file is not serve and you’ll encounter 404 Not Found error.
To resolve this you must configure your ASP.NET Core application to allow serving static content.
Uploaded static files in /wwwroot/upload folder
Your published ASP.NET Core application directory structure looks like:
wwwroot/
├── appsettings.json
├── application.dll
├── /wwwroot
└── Upload
└── image1.png, image2.png, document1.pdf, document2.pdf...
├── web.config
and you want to allow download static files which are in /wwwroot/upload folder. URL in this case for download static files will be:
https://xxxxxx.runasp.net/upload/image1.png
Open your Program.cs file and update your code:
var app = builder.Build();
app.UseStaticFiles(); // Enables serving static files from wwwroot
app.UseStaticFiles(new StaticFileOptions {
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "upload")),
RequestPath = "/"
});
Middleware UseStaticFiles() allow to link/download all static content in /wwwroot folder.
Second extended middleware UseStaticFiles() allows downloading all static content in /wwwroot/upload folder including files that are uploaded dynamically.
You can learn more here:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files
and also here: