In an ASP.NET Core MVC pipeline, model binding, model validation, action filters, and controller action execution all happen after resource filters run. If a request is missing a required tenant/API header, exceeds a per-client request quota, or hits a warm response cache, waiting until model binding or controller execution wastes CPU cycles deserializing payloads, running validators, and hitting downstream services or databases.
IAsyncResourceFilter executes immediately after authorization and before model binding, action filters, controller activation, and result filters. Setting context.Result before calling await next() short-circuits the rest of the MVC pipeline—skipping model binding and controller execution altogether—while still letting IAsyncResourceFilter inspect or cache the resulting IActionResult on the way back. This guide covers how IAsyncResourceFilter fits into the MVC lifecycle, how to implement pre-binding validation and response caching cleanly, how to register it in Program.cs, and how to test short-circuiting and cache hits end-to-end.
1. Architectural Blueprint & IAsyncResourceFilter Execution Window
Placing pre-binding checks and read-through response caching in IAsyncResourceFilter protects downstream MVC stages from unnecessary work:
HTTP Request
│
▼
[Middleware] ──> [Routing] ──> [Authorization]
│
▼
┌─────────────────────────────────────────────────────┐
│ IAsyncResourceFilter.OnResourceExecutionAsync │
│ 1. Pre-binding checks (headers, quotas, cache get) │
│ ├── Cache Hit or Quota/Header Reject ───────────┼──> Set context.Result
│ │ (Skips Model Binding & Action Execution) │ (Short-Circuit!)
│ ▼ (Cache Miss & Valid) │
│ 2. await next() ─────────────────────────────────┼──> [Model Binding]
│ │ [Action Filters]
│ │ [Controller Action]
│ │ [Result Filters]
│ 3. Post-execution (store cacheable result) │
└─────────────────────────────────────────────────────┘
│
▼
HTTP Response
Stage Relative to IAsyncResourceFilter | What Happens | Why Pre-Binding Short-Circuiting Matters |
Before IAsyncResourceFilter | Routing, authentication, and authorization run. | You know the route, HttpContext, and authenticated identity before doing heavy work. |
Inside IAsyncResourceFilter (Before await next()) | Custom pre-binding logic runs before model binding and action invocation. | Invalid headers, missing preconditions, or cached responses bypass deserialization and controller logic completely. |
Inside await next() | Model binding, model validation, action filters, controller action, and result filters execute. | Runs only when the request passes pre-binding checks and is not served from cache. |
Inside IAsyncResourceFilter (After await next()) | ResourceExecutedContext exposes the completed Result and any Exception.
| Lets you cache successful ObjectResult or ContentResult responses for subsequent requests. |
2. Domain Contracts & Cache / Quota Abstractions
Suppose an MVC catalogue or pricing endpoint serves read-heavy JSON/view results keyed by route, query string, and a tenant/API scope header (X-Client-Key), while rejecting requests that omit X-Client-Key before model binding even starts.
C#
using Microsoft.AspNetCore.Mvc;
public sealed record CachedResourceResponse(
int StatusCode,
string ContentType,
string Payload,
DateTimeOffset CachedAtUtc
);
public interface IResourceCacheStore
{
Task<CachedResourceResponse?> GetAsync(string cacheKey, CancellationToken cancellationToken = default);
Task SetAsync(
string cacheKey,
CachedResourceResponse entry,
TimeSpan ttl,
CancellationToken cancellationToken = default);
}
public sealed record CatalogQuoteQuery(
string Sku,
int Quantity,
string RegionCode
);
public sealed record CatalogQuoteResponse(
string Sku,
int Quantity,
string RegionCode,
decimal UnitPrice,
decimal TotalPrice,
DateTimeOffset GeneratedAtUtc
);
3. Implementing IAsyncResourceFilter for Pre-Binding Validation & Caching
When writing an IAsyncResourceFilter that caches responses, keep two subtle MVC details in mind:
Only cache safe, deterministic reads (GET or HEAD) and never cache when ModelState is invalid or an exception occurred.
Avoid caching streaming or non-serializable results (such as FileResult or ViewResult depending on ViewData/TempData state); caching serialized ObjectResult or ContentResult payloads is predictable and safe across requests.
C#
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
public sealed class PreBindingCacheAndGuardResourceFilter : IAsyncResourceFilter
{
private const string ClientKeyHeader = "X-Client-Key";
private const string CacheHitHeader = "X-Resource-Cache";
private static readonly TimeSpan CacheTtl = TimeSpan.FromMinutes(5);
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
private readonly IResourceCacheStore _cacheStore;
private readonly ILogger<PreBindingCacheAndGuardResourceFilter> _logger;
public PreBindingCacheAndGuardResourceFilter(
IResourceCacheStore cacheStore,
ILogger<PreBindingCacheAndGuardResourceFilter> logger)
{
_cacheStore = cacheStore;
_logger = logger;
}
public async Task OnResourceExecutionAsync(
ResourceExecutingContext context,
ResourceExecutionDelegate next)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(next);
var httpContext = context.HttpContext;
var ct = httpContext.RequestAborted;
// 1. Pre-binding header guard: reject before model binding or action execution
if (!httpContext.Request.Headers.TryGetValue(ClientKeyHeader, out var clientKeyValues) ||
string.IsNullOrWhiteSpace(clientKeyValues))
{
context.Result = new BadRequestObjectResult(new ProblemDetails
{
Type = "https://problems.example.local/errors/missing-client-key",
Title = "Missing Client Key",
Status = StatusCodes.Status400BadRequest,
Detail = $"The '{ClientKeyHeader}' header is required before binding request parameters.",
Instance = httpContext.Request.Path.Value
});
return; // Short-circuits pipeline prior to model binding
}
string clientKey = clientKeyValues.ToString().Trim();
bool isCacheableMethod = HttpMethods.IsGet(httpContext.Request.Method) ||
HttpMethods.IsHead(httpContext.Request.Method);
string cacheKey = BuildCacheKey(httpContext.Request, clientKey);
// 2. Pre-binding cache lookup: return cached result immediately on hit
if (isCacheableMethod)
{
CachedResourceResponse? cached = await _cacheStore.GetAsync(cacheKey, ct);
if (cached is not null)
{
_logger.LogInformation("Resource filter cache HIT for key {CacheKey}.", cacheKey);
httpContext.Response.Headers[CacheHitHeader] = "HIT";
context.Result = new ContentResult
{
StatusCode = cached.StatusCode,
ContentType = cached.ContentType,
Content = cached.Payload
};
return; // Short-circuits model binding and controller action
}
httpContext.Response.Headers[CacheHitHeader] = "MISS";
}
// 3. Proceed into model binding, action filters, controller action, and result filters
ResourceExecutedContext executedContext = await next();
// 4. Store successful ObjectResult payloads after execution
if (isCacheableMethod &&
executedContext.Exception is null &&
!executedContext.Canceled &&
executedContext.ModelState.IsValid &&
executedContext.Result is ObjectResult objectResult &&
objectResult.Value is not null)
{
int statusCode = objectResult.StatusCode ?? StatusCodes.Status200OK;
if (statusCode is >= 200 and < 300)
{
string jsonPayload = JsonSerializer.Serialize(objectResult.Value, JsonOptions);
var entry = new CachedResourceResponse(
StatusCode: statusCode,
ContentType: "application/json; charset=utf-8",
Payload: jsonPayload,
CachedAtUtc: DateTimeOffset.UtcNow);
await _cacheStore.SetAsync(cacheKey, entry, CacheTtl, ct);
_logger.LogInformation("Resource filter cached response for key {CacheKey}.", cacheKey);
}
}
}
private static string BuildCacheKey(HttpRequest request, string clientKey)
{
string raw = $"{request.Method}:{request.Path.Value}:{request.QueryString.Value}:client={clientKey}";
byte[] hashBytes = SHA256.HashData(Encoding.UTF8.GetBytes(raw));
return $"resfilter:{Convert.ToHexString(hashBytes)}";
}
}
(For a production multi-instance deployment, back IResourceCacheStore with IDistributedCache / Redis or HybridCache rather than a single-process dictionary.)
4. Registering and Consuming the Filter (Program.cs & Controller)
Programmatic Registration (Program.cs)
Register PreBindingCacheAndGuardResourceFilter and its store in DI, and attach it to targeted actions or controllers via [ServiceFilter(typeof(...))].
C#
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IResourceCacheStore, InMemoryResourceCacheStore>();
builder.Services.AddScoped<PreBindingCacheAndGuardResourceFilter>();
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapControllers();
app.Run();
public partial class Program { }
Controller Action (PricingController.cs)
Because the IAsyncResourceFilter runs before model binding, if X-Client-Key is missing or the response is already cached, the controller action body is never invoked.
C#
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/pricing")]
public sealed class PricingController : ControllerBase
{
private readonly ILogger<PricingController> _logger;
public PricingController(ILogger<PricingController> logger)
{
_logger = logger;
}
[HttpGet("quote")]
[ServiceFilter(typeof(PreBindingCacheAndGuardResourceFilter))]
public IActionResult GetQuote([FromQuery] CatalogQuoteQuery query)
{
if (!ModelState.IsValid)
{
return ValidationProblem(ModelState);
}
if (string.IsNullOrWhiteSpace(query.Sku) || query.Quantity <= 0)
{
return BadRequest(new { Error = "A valid SKU and positive quantity are required." });
}
_logger.LogInformation(
"Computing fresh quote for SKU {Sku}, Qty {Quantity}, Region {Region}.",
query.Sku,
query.Quantity,
query.RegionCode);
decimal unitPrice = string.Equals(query.RegionCode, "PK", StringComparison.OrdinalIgnoreCase)
? 12.50m
: 15.00m;
var response = new CatalogQuoteResponse(
Sku: query.Sku.Trim().ToUpperInvariant(),
Quantity: query.Quantity,
RegionCode: string.IsNullOrWhiteSpace(query.RegionCode) ? "US" : query.RegionCode.Trim().ToUpperInvariant(),
UnitPrice: unitPrice,
TotalPrice: unitPrice * query.Quantity,
GeneratedAtUtc: DateTimeOffset.UtcNow);
return Ok(response);
}
}
5. End-to-End Integration Testing with WebApplicationFactory<Program>
Integration tests against WebApplicationFactory<Program> verify both short-circuiting on missing headers and cache hit/miss behavior across repeated HTTP requests:
C#
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
public sealed class PricingControllerResourceFilterTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;
public PricingControllerResourceFilterTests(WebApplicationFactory<Program> factory)
{
_factory = factory;
}
[Fact]
public async Task GetQuote_MissingClientKey_ShortCircuitsWithBadRequestProblemDetails()
{
using HttpClient client = _factory.CreateClient();
HttpResponseMessage response = await client.GetAsync("/api/pricing/quote?sku=WIDGET-1&quantity=3®ionCode=US");
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
ProblemDetails? problem = await response.Content.ReadFromJsonAsync<ProblemDetails>();
Assert.NotNull(problem);
Assert.Equal("Missing Client Key", problem.Title);
}
[Fact]
public async Task GetQuote_RepeatedRequestWithClientKey_MissesThenHitsResourceCache()
{
using HttpClient client = _factory.CreateClient();
string url = $"/api/pricing/quote?sku=SKU-{Guid.NewGuid():N}&quantity=2®ionCode=US";
using var firstRequest = new HttpRequestMessage(HttpMethod.Get, url);
firstRequest.Headers.Add("X-Client-Key", "client-alpha");
HttpResponseMessage firstResponse = await client.SendAsync(firstRequest);
Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode);
Assert.Equal("MISS", firstResponse.Headers.GetValues("X-Resource-Cache").Single());
CatalogQuoteResponse? firstQuote = await firstResponse.Content.ReadFromJsonAsync<CatalogQuoteResponse>();
Assert.NotNull(firstQuote);
using var secondRequest = new HttpRequestMessage(HttpMethod.Get, url);
secondRequest.Headers.Add("X-Client-Key", "client-alpha");
HttpResponseMessage secondResponse = await client.SendAsync(secondRequest);
Assert.Equal(HttpStatusCode.OK, secondResponse.StatusCode);
Assert.Equal("HIT", secondResponse.Headers.GetValues("X-Resource-Cache").Single());
CatalogQuoteResponse? secondQuote = await secondResponse.Content.ReadFromJsonAsync<CatalogQuoteResponse>();
Assert.NotNull(secondQuote);
Assert.Equal(firstQuote.GeneratedAtUtc, secondQuote.GeneratedAtUtc);
}
}
6. Conclusion
IAsyncResourceFilter gives ASP.NET Core MVC applications an early execution hook right after authorization and before model binding, action filters, and controller actions run. Using it for pre-binding header/precondition guards and read-through response caching prevents invalid or already-cached requests from paying deserialization and execution costs, while keeping controller actions clean and focused on domain logic.
Join the conversation! Your thoughts help the community grow.