ASP.NET Web API and 404 not-found on static files
How to resolve if your ASP.NET Web API 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 Web API application and want to link or download static files (e.g. images, PDFs, documents etc.) via URLs. However, by default Web API projects do not serve static files, so you’ll encounter 404 Not Found
errors when trying to access this static files.
To resolve this you must configure your ASP.NET Core Web API application to allow serving static content.
1) Static files in /wwwroot folder
Your published ASP.NET Core Web API application directory structure looks like:
wwwroot/
├── appsettings.json
├── application.dll
├── /wwwroot
└── image1.png, image2.png, document1.pdf, document2.pdf...
├── web.config
and you want to allow download static files which are in /wwwroot folder (website root content). URL in this case for download static files will be:
https://xxxxxx.runasp.net/image1.png
Open your Program.cs file and update your code:
var app = builder.Build();
app.UseStaticFiles(); // Enables serving static files from wwwroot
Middleware UseStaticFiles() allow to link/download all static content in /wwwroot folder.
2) Static files in custom folder /Files
Your published ASP.NET Core Web API application directory structure looks like:
wwwroot/
├── appsettings.json
├── application.dll
├── /wwwroot
├── /Files
└── image1.png, image2.png, document1.pdf, document2.pdf...
├── web.config
and you want to allow download static files which are in /Files folder(outside /wwwroot). URL in this case for download static files will be:
https://xxxxxx.runasp.net/Files/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(), @"Files")),
RequestPath = new PathString("/Files")
});
Extended Middleware UseStaticFiles() allow to link/download all static content in /Files folder.
You can learn more here:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files
and also here:
https://stackoverflow.com/questions/71853420/images-not-being-served-in-asp-net-core-web-api