High-traffic ASP.NET Core MVC applications often face two distinct caching challenges at the same time:
Full Action / Endpoint Response Caching with Fine-Grained Policies: Entire GET actions or views—such as public announcements, regional pricing catalogs, or reference tables—can be expensive to assemble repeatedly, yet need policy-driven expiration, query/header variation, and programmatic cache invalidation via tags (IOutputCacheStore.EvictByTagAsync).
Fragment-Level Markup Caching Inside Razor Views: Even when an outer Razor page contains dynamic user or session elements, expensive sub-sections (like a navigation catalog widget or summary panel) benefit from caching rendered HTML fragments in a distributed cache (<distributed-cache>) so repeated page renders avoid re-executing sub-queries or template rendering.
ASP.NET Core's Policy-Based Output Caching (AddOutputCache + [OutputCache(PolicyName = "...")] + UseOutputCache()) and the built-in <distributed-cache> Tag Helper (backed by IDistributedCache) complement each other cleanly: output caching protects full responses at the endpoint/middleware layer with tag-based eviction, while <distributed-cache> caches targeted Razor markup fragments across instances.
1. Architectural Blueprint & Caching Layers
Plaintext
[Client Request]
│
▼
[UseOutputCache()] Middleware
├─ Policy matches (e.g., "CatalogByRegionAndCurrency")
├─ Cache Hit? ──> Returns cached response immediately (with Age / status headers)
└─ Cache Miss? ──> Proceeds to MVC Controller & Razor View
│
▼
[Razor View Rendering]
├─ Dynamic outer layout/user info
└─ <distributed-cache name="..." expires-after="..." vary-by-header="...">
├─ Fragment Hit? ──> Reuses cached HTML fragment from IDistributedCache
└─ Fragment Miss? ──> Renders inner markup & stores in IDistributedCache
Mechanism | Scope | Best Fit |
Policy-Based Output Caching (AddOutputCache / [OutputCache]) | Full HTTP response (status, headers, body) governed by named policies and tags. | Cacheable GET controller actions/pages where query strings, headers, TTL, and tag eviction are central. |
<distributed-cache> Tag Helper
| Specific Razor markup block inside a view, stored via IDistributedCache. | Expensive partial/widget markup inside larger views that vary by query, header, or route values. |
Tag Eviction (IOutputCacheStore) | Invalidates all output-cached entries associated with a tag (e.g., "catalog"). | Immediately purging stale cached responses after data updates without waiting for TTL expiry. |
2. Custom Output Cache Policy and Tag-Based Eviction Service
Let's define a custom IOutputCachePolicy (RegionalCatalogOutputCachePolicy) that varies cache entries by the X-Region header and category query parameter, tags entries with "catalog", and caches 200 OK responses for a configurable duration. We will also provide a CatalogCacheInvalidator service that evicts entries by tag using IOutputCacheStore.
C#
using Microsoft.AspNetCore.OutputCaching;
using Microsoft.Extensions.Primitives;
public sealed class RegionalCatalogOutputCachePolicy : IOutputCachePolicy
{
private readonly TimeSpan _ttl;
public RegionalCatalogOutputCachePolicy(TimeSpan ttl)
{
_ttl = ttl > TimeSpan.Zero ? ttl : TimeSpan.FromSeconds(60);
}
public ValueTask CacheRequestAsync(OutputCacheContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
bool isGetOrHead = HttpMethods.IsGet(context.HttpContext.Request.Method) ||
HttpMethods.IsHead(context.HttpContext.Request.Method);
context.EnableOutputCaching = isGetOrHead;
context.AllowCacheLookup = isGetOrHead;
context.AllowCacheStorage = isGetOrHead;
context.AllowLocking = true;
// Vary cache keys by 'category' query parameter and 'X-Region' header
context.CacheVaryByRules.QueryKeys = new StringValues("category");
context.CacheVaryByRules.HeaderNames = new StringValues("X-Region");
// Tag entries so updates can evict all catalog responses at once
context.Tags.Add("catalog");
return ValueTask.CompletedTask;
}
public ValueTask ServeFromCacheAsync(OutputCacheContext context, CancellationToken cancellationToken) =>
ValueTask.CompletedTask;
public ValueTask ServeResponseAsync(OutputCacheContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
HttpResponse response = context.HttpContext.Response;
if (!StringValues.IsNullOrEmpty(response.Headers.SetCookie))
{
context.AllowCacheStorage = false;
return ValueTask.CompletedTask;
}
if (response.StatusCode == StatusCodes.Status200OK)
{
context.ResponseExpirationTimeSpan = _ttl;
context.AllowCacheStorage = true;
}
else
{
context.AllowCacheStorage = false;
}
return ValueTask.CompletedTask;
}
}
public sealed class CatalogCacheInvalidator
{
private readonly IOutputCacheStore _cacheStore;
private readonly ILogger<CatalogCacheInvalidator> _logger;
public CatalogCacheInvalidator(
IOutputCacheStore cacheStore,
ILogger<CatalogCacheInvalidator> logger)
{
_cacheStore = cacheStore;
_logger = logger;
}
public async Task InvalidateCatalogAsync(CancellationToken cancellationToken)
{
await _cacheStore.EvictByTagAsync("catalog", cancellationToken);
_logger.LogInformation("Evicted output cache entries tagged with 'catalog'.");
}
}
3. MVC Controller Using Policy-Based Output Caching and Tag Eviction
Let's build a CatalogStore and an MVC StorefrontController with:
A GET /storefront/catalog action decorated with [OutputCache(PolicyName = "CatalogPolicy")] that renders a Razor view containing a <distributed-cache> fragment.
A GET /storefront/api/items JSON action also protected by [OutputCache(PolicyName = "CatalogPolicy")].
A POST /storefront/api/items action that adds an item and calls CatalogCacheInvalidator.InvalidateCatalogAsync(...) so subsequent reads reflect the updated catalog immediately.
C#
using System.Collections.Concurrent;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OutputCaching;
public sealed record CatalogEntry(
string Code,
string Category,
string Title,
decimal Price,
DateTimeOffset CreatedAtUtc
);
public sealed record CreateCatalogEntryRequest(
string Code,
string Category,
string Title,
decimal Price
);
public sealed record CatalogPageViewModel(
string Region,
string SelectedCategory,
int RenderSequence,
IReadOnlyList<CatalogEntry> Items
);
public sealed class CatalogStore
{
private readonly ConcurrentDictionary<string, CatalogEntry> _items = new(StringComparer.OrdinalIgnoreCase);
private int _renderSequence;
public CatalogStore()
{
Seed(new CatalogEntry("PKG-CORE", "platform", "Core Platform License", 499.00m, DateTimeOffset.UtcNow));
Seed(new CatalogEntry("PKG-OPS", "observability", "Telemetry & Metrics Suite", 249.00m, DateTimeOffset.UtcNow));
}
public int NextRenderSequence() => Interlocked.Increment(ref _renderSequence);
public IReadOnlyList<CatalogEntry> GetItems(string? category)
{
IEnumerable<CatalogEntry> query = _items.Values;
if (!string.IsNullOrWhiteSpace(category))
{
query = query.Where(i => string.Equals(i.Category, category.Trim(), StringComparison.OrdinalIgnoreCase));
}
return query.OrderBy(i => i.Code, StringComparer.OrdinalIgnoreCase).ToList();
}
public CatalogEntry AddOrUpdate(CreateCatalogEntryRequest request)
{
var entry = new CatalogEntry(
Code: request.Code.Trim().ToUpperInvariant(),
Category: request.Category.Trim().ToLowerInvariant(),
Title: request.Title.Trim(),
Price: request.Price,
CreatedAtUtc: DateTimeOffset.UtcNow);
_items[entry.Code] = entry;
return entry;
}
private void Seed(CatalogEntry entry) => _items[entry.Code] = entry;
}
[Route("storefront")]
public sealed class StorefrontController : Controller
{
private readonly CatalogStore _store;
private readonly CatalogCacheInvalidator _invalidator;
public StorefrontController(CatalogStore store, CatalogCacheInvalidator invalidator)
{
_store = store;
_invalidator = invalidator;
}
[HttpGet("catalog")]
[OutputCache(PolicyName = "CatalogPolicy")]
public IActionResult Catalog([FromQuery] string? category = null)
{
string region = HttpContext.Request.Headers["X-Region"].ToString().Trim();
if (string.IsNullOrWhiteSpace(region))
{
region = "global";
}
string normalizedCategory = string.IsNullOrWhiteSpace(category) ? "all" : category.Trim().ToLowerInvariant();
IReadOnlyList<CatalogEntry> items = _store.GetItems(category);
var vm = new CatalogPageViewModel(
Region: region.ToLowerInvariant(),
SelectedCategory: normalizedCategory,
RenderSequence: _store.NextRenderSequence(),
Items: items);
return View(vm);
}
[HttpGet("api/items")]
[OutputCache(PolicyName = "CatalogPolicy")]
public IActionResult GetItems([FromQuery] string? category = null)
{
IReadOnlyList<CatalogEntry> items = _store.GetItems(category);
return Ok(new
{
RenderSequence = _store.NextRenderSequence(),
Count = items.Count,
Items = items
});
}
[HttpPost("api/items")]
public async Task<IActionResult> CreateItem(
[FromBody] CreateCatalogEntryRequest request,
CancellationToken cancellationToken)
{
if (request is null ||
string.IsNullOrWhiteSpace(request.Code) ||
string.IsNullOrWhiteSpace(request.Category) ||
string.IsNullOrWhiteSpace(request.Title) ||
request.Price < 0)
{
return BadRequest(new ProblemDetails
{
Title = "Invalid Catalog Entry",
Detail = "Code, Category, Title, and non-negative Price are required.",
Status = StatusCodes.Status400BadRequest
});
}
CatalogEntry created = _store.AddOrUpdate(request);
await _invalidator.InvalidateCatalogAsync(cancellationToken);
return Created($"/storefront/api/items?category={Uri.EscapeDataString(created.Category)}", created);
}
}
4. Razor View Using <distributed-cache> Tag Helper
Inside Views/Storefront/Catalog.cshtml, <distributed-cache> caches the catalog table fragment in IDistributedCache for 120 seconds, varying by category query parameter and X-Region header.
Razor CSHTML
@model CatalogPageViewModel
@{
ViewData["Title"] = "Storefront Catalog";
}
<section class="storefront-catalog" data-region="@Model.Region">
<h1>Storefront Catalog (@Model.SelectedCategory)</h1>
<p>Outer Render Sequence: <strong id="outer-sequence">@Model.RenderSequence</strong></p>
<distributed-cache name="@($"catalog-fragment-{Model.Region}-{Model.SelectedCategory}")"
expires-after="@TimeSpan.FromSeconds(120)"
vary-by-query="category"
vary-by-header="X-Region">
<div class="catalog-fragment" data-fragment-sequence="@Model.RenderSequence">
<h2>Available Modules (Sequence #@Model.RenderSequence)</h2>
<ul>
@foreach (CatalogEntry item in Model.Items)
{
<li>
<strong>@item.Code</strong> — @item.Title (@item.Category) : [email protected]("0.00")
</li>
}
</ul>
</div>
</distributed-cache>
</section>
5. Program.cs Wiring and End-to-End Integration Testing
Application Setup (Program.cs)
Register AddDistributedMemoryCache() (for <distributed-cache> and distributed cache backing), AddOutputCache(...) with the named "CatalogPolicy", CatalogStore, and CatalogCacheInvalidator, and enable app.UseOutputCache() in the middleware pipeline.
C#
var builder = WebApplication.CreateBuilder(args);
// Distributed cache backs <distributed-cache> TagHelper fragments (swap for Redis in multi-node clusters)
builder.Services.AddDistributedMemoryCache();
// Policy-based Output Caching with tag eviction support
builder.Services.AddOutputCache(options =>
{
options.AddPolicy("CatalogPolicy", new RegionalCatalogOutputCachePolicy(TimeSpan.FromSeconds(120)));
});
builder.Services.AddSingleton<CatalogStore>();
builder.Services.AddSingleton<CatalogCacheInvalidator>();
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseOutputCache();
app.UseAuthorization();
app.MapControllers();
app.Run();
public partial class Program { }
End-to-End Integration Testing with WebApplicationFactory<Program>
Testing against WebApplicationFactory<Program> confirms that output-cached responses return identical cached payloads on repeated requests and evict cleanly when a new item is created via POST /storefront/api/items.
C#
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
public sealed class OutputCachingAndDistributedTagHelperTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;
public OutputCachingAndDistributedTagHelperTests(WebApplicationFactory<Program> factory)
{
_factory = factory;
}
[Fact]
public async Task GetItems_RepeatedRequestWithinTtl_ServesCachedResponseWithSameSequence()
{
using HttpClient client = _factory.CreateClient();
string category = $"cat-{Guid.NewGuid():N}"[..8];
using var req1 = new HttpRequestMessage(HttpMethod.Get, $"/storefront/api/items?category={category}");
req1.Headers.Add("X-Region", "eu-west");
HttpResponseMessage res1 = await client.SendAsync(req1);
Assert.Equal(HttpStatusCode.OK, res1.StatusCode);
using JsonDocument doc1 = JsonDocument.Parse(await res1.Content.ReadAsStringAsync());
int seq1 = doc1.RootElement.GetProperty("renderSequence").GetInt32();
int count1 = doc1.RootElement.GetProperty("count").GetInt32();
Assert.Equal(0, count1);
using var req2 = new HttpRequestMessage(HttpMethod.Get, $"/storefront/api/items?category={category}");
req2.Headers.Add("X-Region", "eu-west");
HttpResponseMessage res2 = await client.SendAsync(req2);
Assert.Equal(HttpStatusCode.OK, res2.StatusCode);
using JsonDocument doc2 = JsonDocument.Parse(await res2.Content.ReadAsStringAsync());
int seq2 = doc2.RootElement.GetProperty("renderSequence").GetInt32();
Assert.Equal(seq1, seq2);
}
[Fact]
public async Task CreateItem_EvictsCatalogOutputCacheByTag_AndReflectsNewItem()
{
using HttpClient client = _factory.CreateClient();
string category = $"evict-{Guid.NewGuid():N}"[..10];
string code = $"MOD-{Guid.NewGuid():N}"[..8].ToUpperInvariant();
using var beforeReq = new HttpRequestMessage(HttpMethod.Get, $"/storefront/api/items?category={category}");
beforeReq.Headers.Add("X-Region", "us-east");
HttpResponseMessage beforeRes = await client.SendAsync(beforeReq);
using JsonDocument beforeDoc = JsonDocument.Parse(await beforeRes.Content.ReadAsStringAsync());
Assert.Equal(0, beforeDoc.RootElement.GetProperty("count").GetInt32());
HttpResponseMessage createRes = await client.PostAsJsonAsync(
"/storefront/api/items",
new CreateCatalogEntryRequest(code, category, "New Cached Module", 199.00m));
Assert.Equal(HttpStatusCode.Created, createRes.StatusCode);
using var afterReq = new HttpRequestMessage(HttpMethod.Get, $"/storefront/api/items?category={category}");
afterReq.Headers.Add("X-Region", "us-east");
HttpResponseMessage afterRes = await client.SendAsync(afterReq);
using JsonDocument afterDoc = JsonDocument.Parse(await afterRes.Content.ReadAsStringAsync());
Assert.Equal(1, afterDoc.RootElement.GetProperty("count").GetInt32());
}
}
6. Conclusion
Pairing Policy-Based Output Caching (AddOutputCache, custom IOutputCachePolicy, and IOutputCacheStore.EvictByTagAsync) with the <distributed-cache> Tag Helper in ASP.NET Core MVC gives you layered caching control from full HTTP responses down to individual Razor view fragments. By varying keys accurately on query/header inputs and invalidating tagged entries on writes, you reduce backend load while keeping cached views and API responses fresh and predictable.
Join the conversation! Your thoughts help the community grow.