Skip to main content

Newsletter Archive

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

Page 2 of 21 (61 editions)

October 25, 2026

You ask the model the same question twice. Your app makes two network calls and pays for two answers. Sometimes that is exactly what you want. Sometimes a cache is a better fit.

Microsoft.Extensions.AI lets you add distributed caching to an IChatClient pipeline.

Try It

This example uses Ollama and an in memory distributed cache. Add the packages:

Terminal window
dotnet add package Microsoft.Extensions.AI
dotnet add package Microsoft.Extensions.Caching.Memory
dotnet add package OllamaSharp

With Ollama running locally and the llama3.1 model available, try this in a .NET 10 console app:

using Microsoft.Extensions.AI;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using OllamaSharp;
var model = new OllamaApiClient(
new Uri("http://localhost:11434"),
"llama3.1");
IChatClient chatClient = new ChatClientBuilder(model)
.UseDistributedCache(new MemoryDistributedCache(
Options.Create(new MemoryDistributedCacheOptions())))
.Build();
string[] prompts =
[
"What is a .NET assembly?",
"What is a .NET assembly?"
];
foreach (var prompt in prompts)
{
var response = await chatClient.GetResponseAsync(prompt);
Console.WriteLine(response.Text);
}

The second identical prompt can be served from the cache instead of asking the model again.

The Big Gotcha

The cache only helps when the request matches what was cached. A slightly different prompt, model configuration, or relevant chat history can mean a different answer.

Be careful with personalized prompts and private data. Don’t let one user’s cached response become another user’s answer. For longer conversations, caching a prompt without its conversation context would be the wrong shortcut.

The sample uses memory, so entries disappear when the process stops and are not shared with other app instances. Use a real distributed cache when that is what your deployment needs.

When Not to Use It

Skip response caching when answers need to be fresh, the model uses randomness that matters to your experience, or user context makes safe cache keys difficult.

Key Takeaway

UseDistributedCache adds caching to an AI client pipeline. It can save repeated calls, but only when the request is genuinely reusable and the cache boundary respects user privacy.

Read the full tip + 6 curated links

Don't miss the next tip 💧

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

October 18, 2026

You have a server-rendered Blazor page where one component does expensive work. The rest of the page is personal, changes often, or simply doesn’t belong in an output cache.

Caching the whole response is too much. Running the expensive component on every request is too little.

.NET 11 adds CacheView, which caches the rendered output of one component subtree during static server-side rendering.

Try It

Create a .NET 11 Blazor Web App with global static rendering:

Terminal window
dotnet new blazor -n CacheViewDemo -f net11.0 --interactivity None
cd CacheViewDemo

Add Components/Pages/Products.razor:

@page "/products"
<PageTitle>Products</PageTitle>
<h1>Products</h1>
<p>This timestamp changes with every request: @DateTimeOffset.Now</p>
<CacheView VaryByQuery="category"
ExpiresAfter="TimeSpan.FromSeconds(30)">
<ProductList Category="@Category" />
</CacheView>
@code {
[SupplyParameterFromQuery]
public string Category { get; set; } = "keyboards";
}

Add Components/ProductList.razor:

<div class="alert alert-secondary">
<strong>Rendered at:</strong> @renderedAt
<br />
<strong>Category:</strong> @Category
</div>
@code {
[Parameter, EditorRequired]
public string Category { get; set; } = "";
private readonly DateTimeOffset renderedAt = DateTimeOffset.Now;
}

Run the app:

Terminal window
dotnet run

Open /products?category=keyboards and refresh the page. The timestamp outside CacheView changes. The timestamp inside stays put for 30 seconds.

Change the category:

/products?category=monitors

VaryByQuery="category" creates a different cache entry for that query value.

What Happens on a Cache Hit

Blazor replays the cached markup. It doesn’t instantiate ProductList, and it doesn’t run that component’s lifecycle.

That is the real win when the child component performs an expensive database query or builds a large chunk of mostly static HTML.

When Not to Use It

Don’t cache user-specific, permission-sensitive, or interactive output unless your cache key varies by everything that makes the result different.

CacheView is for static SSR. If the child needs interactive state or must run on every request, caching its markup is the wrong tool.

Key Takeaway

CacheView lets you cache one expensive region of a static Blazor page without caching the entire response. Vary the entry by the inputs that matter, and be honest about whether the output is safe to share.

Read the full tip + 6 curated links

Don't miss the next tip 💧

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

October 11, 2026

Minimal APIs have always made the happy path look good.

The unhappy path took more work. You could decorate a request model with Data Annotations, but nothing automatically validated it. Most of us wrote an endpoint filter, pulled in another package, or checked every property by hand.

ASP.NET Core 10 adds validation directly to Minimal APIs.

Try It

Create a .NET 10 empty web app:

Terminal window
dotnet new web -n MinimalValidationDemo -f net10.0
cd MinimalValidationDemo

Replace Program.cs with this:

using System.ComponentModel.DataAnnotations;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddValidation();
var app = builder.Build();
app.MapPost("/products", (CreateProduct request) =>
{
var product = new Product(
Id: Random.Shared.Next(1, 10_000),
request.Name,
request.Quantity);
return TypedResults.Created($"/products/{product.Id}", product);
});
app.Run();
public sealed record CreateProduct(
[Required, StringLength(100, MinimumLength = 3)]
string Name,
[Range(1, 1_000)]
int Quantity);
public sealed record Product(int Id, string Name, int Quantity);

Run it:

Terminal window
dotnet run

Send an invalid request:

Terminal window
curl -i -X POST http://localhost:5000/products -H "Content-Type: application/json" -d "{\"name\":\"\",\"quantity\":0}"

Use the HTTP URL shown by dotnet run if your port is different. ASP.NET Core returns 400 Bad Request before your handler runs.

Send a valid request:

Terminal window
curl -i -X POST http://localhost:5000/products -H "Content-Type: application/json" -d "{\"name\":\"Mechanical Keyboard\",\"quantity\":4}"

Validation Isn’t Limited to Request Bodies

The generated validation filter can validate values from the request body, query string, and headers:

app.MapGet("/inventory", (
[Range(1, 100)] int pageSize,
[Required] string warehouse) =>
{
return TypedResults.Ok(new { pageSize, warehouse });
});

The Multi-Assembly Gotcha

AddValidation() uses a source generator. It discovers validatable endpoint types in the assembly where you call it.

If your endpoints live in a separate class library, call AddValidation() from that assembly. Otherwise your attributes can look correct while the generated validation metadata never sees them.

You can disable validation for a specific endpoint with .DisableValidation(), but use that on purpose. Turning it off because a model is inconvenient usually means the model needs another look.

Key Takeaway

ASP.NET Core 10 can validate Minimal API inputs before your handler runs. Add AddValidation(), decorate the model you already have, and let the framework produce the 400 response.

Read the full tip + 5 curated links

Don't miss the next tip 💧

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