A simple ASP.NET Core web application for serving static HTML
Posted: (EET/GMT+2)
If you need to host a very small static site using ASP.NET Core, here's a minimal way to serve HTML files directly without setting up MVC or static file middleware.
The idea is to read the HTML files once at startup into memory and then map simple routes to return their contents. For static HTML files (and a few CSS+JS) this is perfectly fine if the content doesn't change often.
Here's example code in C# that you can put to Program.cs directly:
// prepare the web application builder and build the app
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
WebApplication app = builder.Build();
// read the two static HTML files into memory at startup
const string HtmlContentType = "text/html; charset=utf-8";
string indexHtml = File.ReadAllText(@"Content\Index.html");
string contactHtml = File.ReadAllText(@"Content\Contact.html");
// set up the routes to serve the HTML content
app.MapGet("/", () => TypedResults.Content(indexHtml, HtmlContentType));
app.MapGet("/Contact", () => TypedResults.Content(contactHtml, HtmlContentType));
// start the web application
app.Run();
This keeps things simple: no controllers, no Razor, no wwwroot. Just a couple of routes returning HTML. Note how the content type declaration is crucial: if you just return the HTML text, the browser sees it as plain text and doesn't render the HTML visually.
This kind of 15-line code is handy when you need a lightweight product page, internal tool UI, or a temporary site without extra moving parts. And since its ASP.NET behind, you can always expand: SQL database access, HTTP backend requests, dynamic rendering logic, etc.
Tip: because the files are loaded at startup, changes require an app restart. For simple deployments, that's usually acceptable and avoids file I/O on each request.
Also a quick note on resource consumption: running this with .NET required about 40 MB of RAM only, so it's lean, too.