Skip to main content

Newsletter Archive

Browse through our collection of past newsletters. Each edition is packed with C# and .NET insights.

Page 6 of 21 (61 editions)

August 2, 2026

MapStaticAssets: Static Files That Actually Cache Properly

UseStaticFiles() has been the default for serving CSS, JS, and images since ASP.NET Core 1.0. It works. But it’s dumb: no content-based ETags, no precompressed variants, no fingerprinted cache headers. You end up with stale CSS in your users’ browsers, or you manually configure response caching middleware, or you append ?v=2 query strings like it’s 2010.

.NET 9’s MapStaticAssets() fixes all of this with one line.

The Swap

// Before: basic file serving, no smart caching
app.UseStaticFiles();
// After: content-hashed ETags, precompressed files, immutable cache headers
app.MapStaticAssets();

What You Get for Free

Content-based ETags. The ETag is a hash of the file content, not the last-modified timestamp. Deploy a new version with an identical file? No unnecessary download. Change one byte? Cache invalidates automatically.

Precompressed responses. If you have app.css.br (Brotli) or app.css.gz (gzip) alongside app.css, MapStaticAssets serves the compressed variant automatically based on Accept-Encoding. Blazor and the .NET build system generate these for you.

Immutable cache headers. For fingerprinted files (like Blazor’s app.abc123.css), it sets Cache-Control: max-age=31536000, immutable. The browser caches it forever and never asks again. When the content changes, the filename changes, and the old cache entry is simply abandoned.

Blazor Integration

In a Blazor app, your App.razor references static assets, and the build system fingerprints them:

<link rel="stylesheet" href="@Assets["app.css"]" />
<script src="@Assets["app.js"]"></script>

@Assets["app.css"] resolves to something like app.a1b2c3d4.css at build time. Combined with MapStaticAssets(), the browser gets an immutable, precompressed file with a year-long cache lifetime. Deploy a new version and the filename changes — instant cache bust, zero stale content.

Razor Pages / MVC

Works the same way with tag helpers:

<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />

With MapStaticAssets, the version append uses the same content hash, and responses include proper cache headers.

Response Headers Comparison

Header UseStaticFiles() MapStaticAssets()
ETag File modified time Content hash
Cache-Control Not set max-age=31536000, immutable (fingerprinted)
Content-Encoding Manual middleware Automatic (br/gz)
Vary Not set Accept-Encoding

Key Takeaway

Replace app.UseStaticFiles() with app.MapStaticAssets() and get content-hashed ETags, automatic Brotli/gzip serving, and immutable cache headers, all without configuration. Your CSS will never be stale again, and your users download fewer bytes. One line, done.

Read the full tip + 7 curated links

Don't miss the next tip 💧

Get a .NET tip and curated links delivered to your inbox every week.

July 26, 2026

CompositeFormat: Stop Re-Parsing Format Strings on Every Call

string.Format("{0} processed {1} items in {2:F2}ms", name, count, elapsed) looks innocent enough. But every time you call it, the runtime parses that format string from scratch — finding the {0}, {1:F2} placeholders, validating them, and building the output. Call it once? Fine. Call it 100,000 times in a logging or reporting hot path? That parsing adds up.

CompositeFormat lets you parse the format string once and reuse the compiled representation forever.

The Before

// In a high-throughput logger or report generator
for (int i = 0; i < records.Length; i++)
{
// Parses the format string on EVERY iteration
var line = string.Format(
"[{0:yyyy-MM-dd HH:mm:ss}] {1}: processed {2:N0} records ({3:P1} complete)",
records[i].Timestamp,
records[i].Name,
records[i].Count,
records[i].Progress);
output.AppendLine(line);
}

The After

using System.Text;
// Parse once at startup
private static readonly CompositeFormat LogFormat = CompositeFormat.Parse(
"[{0:yyyy-MM-dd HH:mm:ss}] {1}: processed {2:N0} records ({3:P1} complete)");
// Use the pre-parsed format in the hot path
for (int i = 0; i < records.Length; i++)
{
var line = string.Format(
null, // IFormatProvider (null = current culture)
LogFormat, // pre-parsed, no re-parsing
records[i].Timestamp,
records[i].Name,
records[i].Count,
records[i].Progress);
output.AppendLine(line);
}

The CompositeFormat.Parse() call does the format string analysis once. Every subsequent string.Format call with that CompositeFormat skips the parsing step entirely and goes straight to writing output.

Works with StringBuilder Too

private static readonly CompositeFormat RowFormat =
CompositeFormat.Parse("| {0,-20} | {1,10:C2} | {2,8:N0} |");
var sb = new StringBuilder();
sb.AppendLine("| Product | Price | Quantity |");
sb.AppendLine("|----------------------|------------|----------|");
foreach (var item in inventory)
{
sb.AppendFormat(null, RowFormat, item.Name, item.Price, item.Quantity);
sb.AppendLine();
}

When to Use It

  • Logging pipelines where the same format pattern is applied to millions of entries
  • Report generators that format table rows, CSV lines, or export records
  • Template engines that apply the same pattern repeatedly with different data
  • Any loop where string.Format with a constant format string shows up in your profiler

When NOT to Use It

If your format string is used once or rarely, the overhead of pre-parsing isn’t worth it. CompositeFormat shines specifically in high-repetition scenarios.

Key Takeaway

CompositeFormat.Parse() compiles your format string once. Every subsequent string.Format(provider, compositeFormat, args) call skips re-parsing and goes straight to output. It’s a one-line change that eliminates redundant string parsing on hot paths. If your profiler highlights string.Format, this is your fix.

Read the full tip + 10 curated links

Don't miss the next tip 💧

Get a .NET tip and curated links delivered to your inbox every week.

July 19, 2026

TypedResults: Minimal API Responses That Swagger Actually Understands

You build a Minimal API. You add Swagger. You look at the generated docs and every endpoint shows “200: returns some mysterious object.” Your frontend team Slacks you asking what the actual response shape is. You sigh.

The problem is Results.Ok(product) returns IResult. The OpenAPI generator doesn’t know what’s inside. TypedResults fixes this by returning concrete generic types that the metadata system can inspect at build time.

The Problem

app.MapGet("/products/{id}", async (int id, ProductDb db) =>
{
var product = await db.Products.FindAsync(id);
return product is not null
? Results.Ok(product) // IResult — Swagger sees nothing
: Results.NotFound(); // IResult — also nothing
});

Swagger output: 200: Success. What’s the shape? 🤷

The Fix

app.MapGet("/products/{id}", async Task<Results<Ok<Product>, NotFound>> (int id, ProductDb db) =>
{
var product = await db.Products.FindAsync(id);
return product is not null
? TypedResults.Ok(product)
: TypedResults.NotFound();
});

Now Swagger knows: “200 returns a Product. 404 returns nothing.” The Results<T1, T2> union type in the return signature tells the OpenAPI generator exactly what to document.

Multiple Response Types

The union types support up to six variants:

app.MapPost("/orders", async Task<Results<Created<Order>, ValidationProblem, Conflict>> (
OrderRequest request, OrderDb db) =>
{
if (!IsValid(request))
return TypedResults.ValidationProblem(new Dictionary<string, string[]>
{
["amount"] = ["Amount must be positive"]
});
if (await db.Orders.AnyAsync(o => o.IdempotencyKey == request.IdempotencyKey))
return TypedResults.Conflict();
var order = new Order(request);
db.Orders.Add(order);
await db.SaveChangesAsync();
return TypedResults.Created($"/orders/{order.Id}", order);
});

Swagger now documents all three possible responses with their correct status codes and schemas. Your API consumers know exactly what to expect without reading source code.

Comparison

Approach Swagger Docs Compile-time checks
Results.Ok(obj) ❌ Unknown shape ❌ None
TypedResults.Ok(obj) ✅ Full schema ✅ Type mismatch = error
Results<Ok<T>, NotFound> return ✅ All responses documented ✅ Must return declared types

Key Takeaway

Switch from Results.Ok() to TypedResults.Ok() and declare your return type as Results<T1, T2, ...>. Swagger generates accurate documentation, the compiler catches response type mismatches, and your API consumers finally know what they’re getting back. One refactor, zero ambiguity.

Read the full tip + 7 curated links

Don't miss the next tip 💧

Get a .NET tip and curated links delivered to your inbox every week.