In an ASP.NET Core MVC pipeline, model binding, model validation, and action execution happen after resource filters run. If a request arrives without a required correlation or tenant header—or if a GET endpoint is serving a read-heavy catalog or configuration payload that can be satisfied from cache—running model binding or executing full action logic first wastes CPU, allocations, and database calls.
An IAsyncResourceFilter wraps the entire execution of a controller action and its result after routing and authorization, but before model binding. That positioning makes it ideal for two high-leverage tasks:
Pre-Binding Header Guards: Rejecting missing or malformed required headers immediately (returning an RFC 9457 ProblemDetails 400 Bad Request) before ASP.NET Core even attempts to bind complex request bodies or query parameters.
Read-Through Caching: Checking IMemoryCache or IDistributedCache on cacheable read requests before invoking the action, returning a cached result immediately on a hit, and populating the cache on a miss when the action completes cleanly.
1. Architectural Blueprint & Resource Filter Pipeline Position
Plaintext
Incoming HTTP Request
│
▼
[Routing] ──> [Authorization]
│
▼
┌──────────────────────────────────────────────────────────┐
│ IAsyncResourceFilter.OnResourceExecutionAsync() │
│ 1. Pre-Binding Header Guard: validate required headers │
│ └─ Invalid? Short-circuit with 400 ProblemDetails │
│ (skips model binding & action) │
│ 2. Read-Through Cache Lookup (for GET / cacheable): │
│ └─ Cache Hit? Set context.Result & return early │
│ 3. Cache Miss: call await next() │
│ ├─ Model Binding & Validation │
│ ├─ Action & Result Filters │
│ └─ Result Execution │
│ 4. On successful result, store response payload in cache │
└──────────────────────────────────────────────────────────┘
Capability |
Why It Belongs in IAsyncResourceFilter |
Key Safeguard |
Pre-Binding Header Guard |
Runs before model binding and action filters, avoiding wasted deserialization/validation on malformed requests. |
Short-circuits by setting context.Result = new BadRequestObjectResult(...) without calling await next(). |
Read-Through Cache |
Intercepts before action execution so repeated reads skip expensive queries/services. |
Only caches deterministic read responses (200 OK) and scopes cache keys by route, query, and relevant header/tenant context. |
2. Header Guard Attribute and IAsyncResourceFilter Implementation
Let's create a [RequireHeader("X-Client-Key")] attribute and a RequiredHeaderResourceFilter that checks the header before model binding runs and returns a structured 400 Bad Request ProblemDetails payload when missing or blank.
C#
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Primitives;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public sealed class RequireHeaderAttribute : Attribute, IFilterFactory
{
public string HeaderName { get; }
public int MaxLength { get; }
public RequireHeaderAttribute(string headerName, int maxLength = 128)
{
if (string.IsNullOrWhiteSpace(headerName))
{
throw new ArgumentException("Header name is required.", nameof(headerName));
}
HeaderName = headerName.Trim();
MaxLength = maxLength;
}
public bool IsReusable => true;
public IFilterMetadata CreateInstance(IServiceProvider serviceProvider) =>
new RequiredHeaderResourceFilter(HeaderName, MaxLength);
}
public sealed class RequiredHeaderResourceFilter : IAsyncResourceFilter
{
private readonly string _headerName;
private readonly int _maxLength;
public RequiredHeaderResourceFilter(string headerName, int maxLength)
{
_headerName = headerName;
_maxLength = maxLength;
}
public async Task OnResourceExecutionAsync(
ResourceExecutingContext context,
ResourceExecutionDelegate next)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(next);
if (!context.HttpContext.Request.Headers.TryGetValue(_headerName, out StringValues values) ||
StringValues.IsNullOrEmpty(values) ||
string.IsNullOrWhiteSpace(values.ToString()))
{
context.Result = CreateMissingHeaderProblem(context.HttpContext, _headerName);
return;
}
string headerValue = values.ToString().Trim();
if (headerValue.Length > _maxLength)
{
context.Result = CreateOversizedHeaderProblem(context.HttpContext, _headerName, _maxLength);
return;
}
context.HttpContext.Items[$"GuardHeader:{_headerName}"] = headerValue;
await next();
}
private static ObjectResult CreateMissingHeaderProblem(HttpContext httpContext, string headerName)
{
var problem = new ProblemDetails
{
Type = "https://problems.example.local/errors/missing-required-header",
Title = "Missing Required Header",
Status = StatusCodes.Status400BadRequest,
Detail = $"The '{headerName}' HTTP header is required before processing this request.",
Instance = httpContext.Request.Path.Value
};
problem.Extensions["headerName"] = headerName;
problem.Extensions["traceId"] = httpContext.TraceIdentifier;
return new ObjectResult(problem)
{
StatusCode = StatusCodes.Status400BadRequest,
ContentTypes = { "application/problem+json" }
};
}
private static ObjectResult CreateOversizedHeaderProblem(
HttpContext httpContext,
string headerName,
int maxLength)
{
var problem = new ProblemDetails
{
Type = "https://problems.example.local/errors/invalid-header-length",
Title = "Invalid Header Length",
Status = StatusCodes.Status400BadRequest,
Detail = $"The '{headerName}' HTTP header must not exceed {maxLength} characters.",
Instance = httpContext.Request.Path.Value
};
problem.Extensions["headerName"] = headerName;
problem.Extensions["maxLength"] = maxLength;
problem.Extensions["traceId"] = httpContext.TraceIdentifier;
return new ObjectResult(problem)
{
StatusCode = StatusCodes.Status400BadRequest,
ContentTypes = { "application/problem+json" }
};
}
}
3. Read-Through Caching IAsyncResourceFilter ([ReadThroughCache])
Now let's build a [ReadThroughCache(ttlSeconds: 30)] attribute and ReadThroughCacheResourceFilter using IMemoryCache. It builds a deterministic cache key from the normalized HTTP method, request path, query string, and optional header values (such as X-Client-Key or X-Region), checks for an existing cached object before invoking next(), and caches OkObjectResult payloads on a miss.
C#
using System.Security.Cryptography;
using System.Text;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Memory;
public sealed record CachedPayloadEnvelope(
object? Value,
DateTimeOffset CachedAtUtc
);
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public sealed class ReadThroughCacheAttribute : Attribute, IFilterFactory
{
public int TtlSeconds { get; }
public string[] VaryByHeaders { get; }
public ReadThroughCacheAttribute(int ttlSeconds = 30, params string[] varyByHeaders)
{
if (ttlSeconds <= 0)
{
throw new ArgumentOutOfRangeException(nameof(ttlSeconds), "TTL must be greater than zero.");
}
TtlSeconds = ttlSeconds;
VaryByHeaders = varyByHeaders ?? [];
}
public bool IsReusable => true;
public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
{
var cache = serviceProvider.GetRequiredService<IMemoryCache>();
var logger = serviceProvider.GetRequiredService<ILogger<ReadThroughCacheResourceFilter>>();
return new ReadThroughCacheResourceFilter(cache, logger, TtlSeconds, VaryByHeaders);
}
}
public sealed class ReadThroughCacheResourceFilter : IAsyncResourceFilter
{
private readonly IMemoryCache _cache;
private readonly ILogger<ReadThroughCacheResourceFilter> _logger;
private readonly int _ttlSeconds;
private readonly string[] _varyByHeaders;
public ReadThroughCacheResourceFilter(
IMemoryCache cache,
ILogger<ReadThroughCacheResourceFilter> logger,
int ttlSeconds,
string[] varyByHeaders)
{
_cache = cache;
_logger = logger;
_ttlSeconds = ttlSeconds;
_varyByHeaders = varyByHeaders;
}
public async Task OnResourceExecutionAsync(
ResourceExecutingContext context,
ResourceExecutionDelegate next)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(next);
if (!HttpMethods.IsGet(context.HttpContext.Request.Method))
{
await next();
return;
}
string cacheKey = BuildCacheKey(context.HttpContext, _varyByHeaders);
if (_cache.TryGetValue(cacheKey, out CachedPayloadEnvelope? cachedEnvelope) &&
cachedEnvelope is not null)
{
context.HttpContext.Response.Headers["X-Cache-Status"] = "HIT";
_logger.LogDebug("Read-through cache HIT for key {CacheKey}.", cacheKey);
context.Result = new OkObjectResult(cachedEnvelope.Value);
return;
}
context.HttpContext.Response.Headers["X-Cache-Status"] = "MISS";
_logger.LogDebug("Read-through cache MISS for key {CacheKey}.", cacheKey);
ResourceExecutedContext executedContext = await next();
if (executedContext.Exception is null &&
!executedContext.Canceled &&
executedContext.Result is OkObjectResult okResult)
{
var envelope = new CachedPayloadEnvelope(okResult.Value, DateTimeOffset.UtcNow);
var entryOptions = new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(_ttlSeconds)
};
_cache.Set(cacheKey, envelope, entryOptions);
}
}
private static string BuildCacheKey(HttpContext httpContext, string[] varyByHeaders)
{
var sb = new StringBuilder();
sb.Append(httpContext.Request.Method);
sb.Append('|');
sb.Append(httpContext.Request.Path.Value?.ToLowerInvariant() ?? "/");
sb.Append('|');
sb.Append(httpContext.Request.QueryString.Value?.ToLowerInvariant() ?? string.Empty);
foreach (string header in varyByHeaders)
{
sb.Append('|');
sb.Append(header.ToLowerInvariant());
sb.Append('=');
if (httpContext.Request.Headers.TryGetValue(header, out var val))
{
sb.Append(val.ToString().Trim().ToLowerInvariant());
}
}
byte[] hashBytes = SHA256.HashData(Encoding.UTF8.GetBytes(sb.ToString()));
return "rtc:" + Convert.ToHexString(hashBytes);
}
}
4. MVC Controller and Program.cs Wiring
Let's connect a catalog/pricing service, an MVC controller using [RequireHeader("X-Client-Key")] and [ReadThroughCache(ttlSeconds: 60, "X-Client-Key")], and Program.cs. Notice that when X-Client-Key is absent on POST /api/catalog/quote, the filter rejects the request before QuoteRequest model binding even executes.
C#
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
public sealed record CatalogItemDto(
string Sku,
string Name,
decimal UnitPrice,
int GenerationCount,
DateTimeOffset GeneratedAtUtc
);
public sealed record QuoteRequest(
[Required, MinLength(2)] string Sku,
[Range(1, 10_000)] int Quantity
);
public sealed record QuoteResponse(
string ClientKey,
string Sku,
int Quantity,
decimal TotalAmount
);
public sealed class CatalogPricingService
{
private int _executions;
public int ExecutionCount => Volatile.Read(ref _executions);
public async Task<CatalogItemDto> GetItemAsync(string sku, CancellationToken cancellationToken)
{
int currentRun = Interlocked.Increment(ref _executions);
await Task.Delay(TimeSpan.FromMilliseconds(15), cancellationToken);
string normalizedSku = sku.Trim().ToUpperInvariant();
return new CatalogItemDto(
Sku: normalizedSku,
Name: $"Enterprise Module {normalizedSku}",
UnitPrice: 149.00m,
GenerationCount: currentRun,
GeneratedAtUtc: DateTimeOffset.UtcNow);
}
}
[ApiController]
[Route("api/catalog")]
[RequireHeader("X-Client-Key", maxLength: 64)]
public sealed class CatalogController : ControllerBase
{
private readonly CatalogPricingService _pricingService;
public CatalogController(CatalogPricingService pricingService)
{
_pricingService = pricingService;
}
[HttpGet("items/{sku}")]
[ReadThroughCache(ttlSeconds: 60, "X-Client-Key")]
public async Task<IActionResult> GetItem(string sku, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(sku))
{
return BadRequest();
}
CatalogItemDto item = await _pricingService.GetItemAsync(sku, cancellationToken);
return Ok(item);
}
[HttpPost("quote")]
public IActionResult CalculateQuote([FromBody] QuoteRequest request)
{
string clientKey = HttpContext.Items["GuardHeader:X-Client-Key"]?.ToString() ?? "unknown";
decimal total = decimal.Round(request.Quantity * 149.00m, 2, MidpointRounding.AwayFromZero);
return Ok(new QuoteResponse(
ClientKey: clientKey,
Sku: request.Sku.Trim().ToUpperInvariant(),
Quantity: request.Quantity,
TotalAmount: total));
}
}
Application Setup (Program.cs)
C#
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMemoryCache();
builder.Services.AddSingleton<CatalogPricingService>();
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllers();
app.Run();
public partial class Program { }
5. End-to-End Integration Testing with WebApplicationFactory<Program>
Testing against WebApplicationFactory<Program> verifies both sides of the IAsyncResourceFilter pipeline: missing required headers return 400 Bad Request (application/problem+json) immediately, and repeated GET requests hit the read-through cache (X-Cache-Status: HIT) without re-executing CatalogPricingService.
C#
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
public sealed class ResourceFilterGuardsAndCacheTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;
public ResourceFilterGuardsAndCacheTests(WebApplicationFactory<Program> factory)
{
_factory = factory;
}
[Fact]
public async Task PostQuote_WithoutRequiredHeader_ShortCircuitsWith400ProblemDetails()
{
using HttpClient client = _factory.CreateClient();
HttpResponseMessage response = await client.PostAsJsonAsync(
"/api/catalog/quote",
new QuoteRequest("SKU-100", 3));
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
ProblemDetails? problem = await response.Content.ReadFromJsonAsync<ProblemDetails>();
Assert.NotNull(problem);
Assert.Equal("Missing Required Header", problem.Title);
}
[Fact]
public async Task GetItem_SecondRequestWithSameClientKey_ServesFromReadThroughCache()
{
using HttpClient client = _factory.CreateClient();
string uniqueSku = $"SKU-{Guid.NewGuid():N}"[..10];
string clientKey = $"client-{Guid.NewGuid():N}"[..12];
using var firstRequest = new HttpRequestMessage(HttpMethod.Get, $"/api/catalog/items/{uniqueSku}");
firstRequest.Headers.Add("X-Client-Key", clientKey);
HttpResponseMessage firstResponse = await client.SendAsync(firstRequest);
Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode);
Assert.Equal("MISS", firstResponse.Headers.GetValues("X-Cache-Status").Single());
CatalogItemDto? firstDto = await firstResponse.Content.ReadFromJsonAsync<CatalogItemDto>();
Assert.NotNull(firstDto);
using var secondRequest = new HttpRequestMessage(HttpMethod.Get, $"/api/catalog/items/{uniqueSku}");
secondRequest.Headers.Add("X-Client-Key", clientKey);
HttpResponseMessage secondResponse = await client.SendAsync(secondRequest);
Assert.Equal(HttpStatusCode.OK, secondResponse.StatusCode);
Assert.Equal("HIT", secondResponse.Headers.GetValues("X-Cache-Status").Single());
CatalogItemDto? secondDto = await secondResponse.Content.ReadFromJsonAsync<CatalogItemDto>();
Assert.NotNull(secondDto);
// Cached payload preserves the original GenerationCount from the first execution
Assert.Equal(firstDto.GenerationCount, secondDto.GenerationCount);
}
}
6. Conclusion
Using IAsyncResourceFilter in ASP.NET Core MVC lets you enforce pre-binding header guards and read-through caching right at the boundary of action execution—rejecting invalid/incomplete requests before model binding runs and serving repeated read traffic from cache without touching underlying services. By scoping cache keys carefully with VaryByHeaders and returning standardized ProblemDetails on guard failures, your MVC controllers stay clean, fast, and focused on core business logic.
Join the conversation! Your thoughts help the community grow.