Serving CSS, JavaScript, and images in an ASP.NET Core MVC application through UseStaticFiles alone often leaves significant performance and caching gains on the table. Dynamic compression on the web server burns CPU cycles on every request (and frequently compresses at lower ratios than offline tools), while un-fingerprinted assets risk stale browser or proxy caching after a deployment.
MapStaticAssets solves this by shifting static asset discovery, compression, and content fingerprinting into the build and publish pipeline. MSBuild generates a static web assets endpoint manifest ({AssemblyName}.staticwebassets.endpoints.json) containing metadata, content-based ETags (SHA-256 hashes encoded in Base64), and pre-compressed variants (Gzip during development; Gzip and Brotli when publishing). At runtime, MapStaticAssets() registers dedicated endpoints for those assets so ASP.NET Core MVC serves compressed, cache-friendly responses with minimal runtime overhead. This guide covers how MapStaticAssets works with MVC views and Razor Class Libraries (RCLs), how to configure it alongside UseStaticFiles when needed, and how to verify asset delivery and cache busting in integration tests.
1. Architectural Blueprint: MapStaticAssets vs. UseStaticFiles
MapStaticAssets is designed for assets known at build or publish time (such as files in wwwroot and referenced Razor Class Libraries). If your MVC application serves dynamic runtime uploads from disk, non-manifest folders, or default documents (index.html), you can pair MapStaticAssets with UseStaticFiles.
Plaintext
Build / Publish Time (MSBuild)
├─ Scans wwwroot + Razor Class Libraries (RCLs)
├─ Generates Gzip (Dev) and Gzip + Brotli (Publish) variants
└─ Emits static web assets manifest (content SHA-256 ETags + fingerprints)
Runtime Request (ASP.NET Core MVC)
├─ Browser sends Accept-Encoding: br, gzip + If-None-Match (ETag)
├─ MapStaticAssets endpoint matches asset & negotiates best compression
└─ Returns 200 (pre-compressed payload + ETag) or 304 Not Modified
Capability | UseStaticFiles() | MapStaticAssets() |
Compression Timing | None built-in (relies on response compression middleware or reverse proxy at runtime). | Pre-compressed at build (Gzip) and publish (Gzip + Brotli). |
ETag Generation | Based on file length and last-modified timestamp. | Content-based ETag derived from SHA-256 hash of asset content. |
Pipeline Execution | Runs as middleware; subsequent middleware still executes if not matched. | Registers endpoints; supports .ShortCircuit() to exit early for matched assets. |
Dynamic / Runtime Disk Files | Supported natively for arbitrary directories. | Not intended for runtime-generated or ad-hoc disk files; use UseStaticFiles for those. |
2. Project Setup, Razor Views, and MVC Controller
Keep all scripts and stylesheets local inside wwwroot or a Razor Class Library (RCL) so your MVC views remain self-contained and work reliably even in restricted or offline network environments.
MVC Project Configuration (WebPortal.Mvc.csproj)
XML
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<!-- Optional: exclude specific paths from MapStaticAssets if UseStaticFiles handles them -->
<!-- <PropertyGroup>
<StaticWebAssetEndpointExclusionPattern>legacy-downloads/**</StaticWebAssetEndpointExclusionPattern>
</PropertyGroup> -->
</Project>
Local Static Assets (wwwroot/css/site.css and wwwroot/js/portal.js)
CSS
:root {
--surface-bg: #f8fafc;
--accent: #0f4c81;
--text-primary: #0f172a;
}
body {
margin: 0;
font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background-color: var(--surface-bg);
color: var(--text-primary);
}
.portal-badge {
display: inline-block;
padding: 0.25rem 0.6rem;
border-radius: 0.375rem;
background-color: var(--accent);
color: #ffffff;
font-size: 0.875rem;
}
JavaScript
(function () {
"use strict";
document.addEventListener("DOMContentLoaded", function () {
const statusEl = document.getElementById("asset-runtime-status");
if (statusEl) {
statusEl.textContent = "Local portal script initialized.";
}
});
})();
Razor Layout & MVC View (Views/Shared/_Layout.cshtml & Views/Home/Index.cshtml)
Using asp-append-version="true" alongside MapStaticAssets() ensures asset URLs carry version/fingerprint parameters tied to file content so browsers and proxies fetch fresh files whenever content changes.
Razor CSHTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - Portal</title>
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
</head>
<body>
<main class="container">
@RenderBody()
</main>
<script src="~/js/portal.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>
Razor CSHTML
@{
ViewData["Title"] = "Dashboard";
}
<section>
<h1>Portal Overview</h1>
<span class="portal-badge">Static Assets Active</span>
<p id="asset-runtime-status">Loading script...</p>
</section>
MVC Controller (Controllers/HomeController.cs)
C#
using Microsoft.AspNetCore.Mvc;
public sealed record PortalStatusViewModel(
string EnvironmentName,
DateTimeOffset RenderedAtUtc
);
public sealed class HomeController : Controller
{
private readonly IHostEnvironment _environment;
public HomeController(IHostEnvironment environment)
{
_environment = environment;
}
[HttpGet("/")]
public IActionResult Index()
{
var model = new PortalStatusViewModel(
EnvironmentName: _environment.EnvironmentName,
RenderedAtUtc: DateTimeOffset.UtcNow);
return View(model);
}
}
3. Configuring MapStaticAssets in Program.cs
Call app.MapStaticAssets() after app.UseHttpsRedirection(), and chain .ShortCircuit() if you want matched static asset requests to return immediately without traversing downstream middleware. If you also serve files outside the static web assets manifest (such as dynamic exports on disk), call app.UseStaticFiles(...) for those specific paths.
C#
using Microsoft.Extensions.FileProviders;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
// Maps build/publish-time static assets with pre-compression and content-based ETags
app.MapStaticAssets()
.ShortCircuit();
// Optional: serve runtime-generated files from a dedicated directory outside wwwroot
string runtimeExportsPath = Path.Combine(app.Environment.ContentRootPath, "RuntimeExports");
Directory.CreateDirectory(runtimeExportsPath);
app.UseWhen(
ctx => ctx.Request.Path.StartsWithSegments("/runtime-exports"),
branch => branch.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(runtimeExportsPath),
RequestPath = "/runtime-exports"
}));
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
public partial class Program { }
4. End-to-End Integration Testing with WebApplicationFactory<Program>
You can verify that MapStaticAssets() serves static files, emits ETag headers, honors If-None-Match (304 Not Modified), and renders versioned asset links in MVC views:
C#
using System.Net;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
public sealed class StaticAssetsIntegrationTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;
public StaticAssetsIntegrationTests(WebApplicationFactory<Program> factory)
{
_factory = factory;
}
[Fact]
public async Task HomeIndex_RendersVersionedLocalAssetLinks()
{
using HttpClient client = _factory.CreateClient();
HttpResponseMessage response = await client.GetAsync("/");
response.EnsureSuccessStatusCode();
string html = await response.Content.ReadAsStringAsync();
Assert.Contains("/css/site.css", html);
Assert.Contains("/js/portal.js", html);
Assert.Contains("v=", html);
}
[Fact]
public async Task StaticAsset_SupportsEtagAndConditionalGet304()
{
using HttpClient client = _factory.CreateClient();
using var initialRequest = new HttpRequestMessage(HttpMethod.Get, "/css/site.css");
initialRequest.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
HttpResponseMessage initialResponse = await client.SendAsync(initialRequest);
Assert.Equal(HttpStatusCode.OK, initialResponse.StatusCode);
EntityTagHeaderValue? etag = initialResponse.Headers.ETag;
Assert.NotNull(etag);
using var conditionalRequest = new HttpRequestMessage(HttpMethod.Get, "/css/site.css");
conditionalRequest.Headers.IfNoneMatch.Add(etag);
HttpResponseMessage conditionalResponse = await client.SendAsync(conditionalRequest);
Assert.Equal(HttpStatusCode.NotModified, conditionalResponse.StatusCode);
}
}
5. Conclusion
MapStaticAssets() modernizes static asset delivery in ASP.NET Core MVC by moving compression and content-based fingerprinting into build and publish time rather than paying runtime compression costs on every request. Combined with asp-append-version="true" in Razor views and targeted UseStaticFiles branches only when serving runtime disk artifacts, your MVC applications get smaller payloads, deterministic cache busting, and cleaner middleware execution.
Join the conversation! Your thoughts help the community grow.