Middleware operates at the raw HTTP transport level—it sees HttpContext, routes, and streams, but has no awareness of which MVC controller action was selected, what action arguments were bound, or what IActionResult (ViewResult, JsonResult, ObjectResult) a controller chose to return. Conversely, putting audit logging, idempotency enforcement, or response envelope/header decoration inside every controller action creates repetitive boilerplate and risks inconsistent behavior across endpoints.
The ASP.NET Core MVC Filter Pipeline fills this exact gap. Filters execute inside MVC's action invocation lifecycle with full access to ActionExecutingContext, ActionExecutedContext, and ResultExecutingContext / ResultExecutedContext, while integrating cleanly with Dependency Injection via ServiceFilterAttribute or TypeFilterAttribute. This guide covers how IAsyncActionFilter and IAsyncResultFilter fit into the MVC pipeline, how to implement production-ready async filters for idempotency and response metadata/auditing, and how to test them end-to-end.
1. Architectural Blueprint & Filter Pipeline Ordering
Understanding where IAsyncActionFilter and IAsyncResultFilter execute relative to model binding, action execution, and result rendering prevents subtle lifecycle bugs:
HTTP Request
│
▼
[Middleware] ──> [Routing] ──> [Model Binding] ──> [Action Validation]
│
▼
┌─────────────────────────────────────┐
│ IAsyncActionFilter.OnActionExecutionAsync
│ before await next() ────────────┼──> Short-circuit or inspect ActionArguments
│ │ │
│ ▼ │
│ [Controller Action Executes] │
│ │ │
│ after await next() ─────────────┼──> Inspect ActionExecutedContext / Result
└─────────────────────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ IAsyncResultFilter.OnResultExecutionAsync
│ before await next() ────────────┼──> Mutate headers/result before View/JSON runs
│ │ │
│ ▼ │
│ [IActionResult Executes] │
│ │ │
│ after await next() ─────────────┼──> Post-render telemetry / cleanup
└─────────────────────────────────────┘
│
▼
HTTP Response
Filter Interface | Execution Window | Key Context Properties | Best-Fit Scenarios |
IAsyncActionFilter
| Wraps controller action invocation (after model binding, before result execution). | ActionExecutingContext (ActionArguments, ModelState, Result), ActionExecutedContext (Result, Exception).
| Idempotency key checks, request/argument auditing, short-circuiting invalid/duplicate commands before action execution. |
IAsyncResultFilter
| Wraps IActionResult execution (after action completes, before view/JSON output is written). | ResultExecutingContext (Result, ModelState), ResultExecutedContext (Result, Exception, Canceled).
| Adding response headers (X-Execution-Duration-Ms, X-Request-Id), wrapping/inspecting results, response-stage auditing. |
2. Domain Contracts & Supporting Stores
Suppose an MVC application exposes state-changing endpoints (such as payment or submission actions) that must honor an Idempotency-Key header so client retries do not duplicate work, alongside a result filter that stamps execution timing and correlation metadata onto responses.
C#
using Microsoft.AspNetCore.Mvc;
public sealed record CachedIdempotentOutcome(
int StatusCode,
string ContentType,
string Body,
DateTimeOffset StoredAtUtc
);
public interface IIdempotencyStore
{
Task<CachedIdempotentOutcome?> GetAsync(string key, CancellationToken cancellationToken = default);
Task SetAsync(
string key,
CachedIdempotentOutcome outcome,
TimeSpan ttl,
CancellationToken cancellationToken = default);
}
public sealed record SubmitOrderCommand(
string ReferenceCode,
decimal Amount,
string Currency
);
public sealed record SubmitOrderResponse(
Guid SubmissionId,
string ReferenceCode,
decimal Amount,
string Currency,
DateTimeOffset ProcessedAtUtc
);
3. Implementing an IAsyncActionFilter for Idempotency
In IAsyncActionFilter.OnActionExecutionAsync, setting context.Result before calling await next() short-circuits the pipeline and skips the controller action completely. After await next() returns, executedContext.Result holds the action result produced by the controller.
C#
using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
public sealed class IdempotencyActionFilter : IAsyncActionFilter
{
private const string IdempotencyHeaderName = "Idempotency-Key";
private static readonly TimeSpan DefaultTtl = TimeSpan.FromHours(24);
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
private readonly IIdempotencyStore _store;
private readonly ILogger<IdempotencyActionFilter> _logger;
public IdempotencyActionFilter(
IIdempotencyStore store,
ILogger<IdempotencyActionFilter> logger)
{
_store = store;
_logger = logger;
}
public async Task OnActionExecutionAsync(
ActionExecutingContext context,
ActionExecutionDelegate next)
{
if (!context.HttpContext.Request.Headers.TryGetValue(IdempotencyHeaderName, out var rawKey) ||
string.IsNullOrWhiteSpace(rawKey))
{
context.Result = new BadRequestObjectResult(new ProblemDetails
{
Title = "Missing Idempotency Key",
Detail = $"The '{IdempotencyHeaderName}' header is required for this action.",
Status = StatusCodes.Status400BadRequest
});
return;
}
string normalizedKey = $"idem:{context.ActionDescriptor.DisplayName}:{rawKey.ToString().Trim()}";
var ct = context.HttpContext.RequestAborted;
CachedIdempotentOutcome? existing = await _store.GetAsync(normalizedKey, ct);
if (existing is not null)
{
_logger.LogInformation(
"Replaying cached response for idempotency key {IdempotencyKey}.",
normalizedKey);
context.HttpContext.Response.Headers["X-Idempotent-Replay"] = "true";
context.Result = new ContentResult
{
StatusCode = existing.StatusCode,
ContentType = existing.ContentType,
Content = existing.Body
};
return;
}
ActionExecutedContext executedContext = await next();
if (executedContext.Exception is null &&
executedContext.Result is ObjectResult objectResult &&
objectResult.Value is not null)
{
int statusCode = objectResult.StatusCode ?? StatusCodes.Status200OK;
if (statusCode is >= 200 and < 300)
{
string serializedBody = JsonSerializer.Serialize(objectResult.Value, JsonOptions);
var outcome = new CachedIdempotentOutcome(
StatusCode: statusCode,
ContentType: "application/json; charset=utf-8",
Body: serializedBody,
StoredAtUtc: DateTimeOffset.UtcNow);
await _store.SetAsync(normalizedKey, outcome, DefaultTtl, ct);
}
}
}
}
4. Implementing an IAsyncResultFilter for Response Headers & Timing
IAsyncResultFilter runs around IActionResult execution. Notice that modifying response headers should happen before await next()—once the response body stream starts flushing to the client inside await next(), mutating headers can throw an InvalidOperationException because headers have already been sent.
C#
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc.Filters;
public sealed class ResponseTelemetryResultFilter : IAsyncResultFilter
{
private const string DurationHeaderName = "X-Action-Elapsed-Ms";
private const string TraceHeaderName = "X-Trace-Id";
private readonly ILogger<ResponseTelemetryResultFilter> _logger;
public ResponseTelemetryResultFilter(ILogger<ResponseTelemetryResultFilter> logger)
{
_logger = logger;
}
public async Task OnResultExecutionAsync(
ResultExecutingContext context,
ResultExecutionDelegate next)
{
long startTimestamp = Stopwatch.GetTimestamp();
string traceId = Activity.Current?.TraceId.ToString() ?? context.HttpContext.TraceIdentifier;
if (!context.HttpContext.Response.HasStarted)
{
context.HttpContext.Response.Headers[TraceHeaderName] = traceId;
}
context.HttpContext.Response.OnStarting(() =>
{
double elapsedMs = Stopwatch.GetElapsedTime(startTimestamp).TotalMilliseconds;
context.HttpContext.Response.Headers[DurationHeaderName] = elapsedMs.ToString("F2");
return Task.CompletedTask;
});
ResultExecutedContext executedContext = await next();
double totalMs = Stopwatch.GetElapsedTime(startTimestamp).TotalMilliseconds;
_logger.LogInformation(
"Result {ResultType} for {ActionName} completed in {ElapsedMs:F2} ms (Canceled: {Canceled}).",
executedContext.Result?.GetType().Name ?? "None",
context.ActionDescriptor.DisplayName,
totalMs,
executedContext.Canceled);
}
}
5. Registering and Applying Filters (Program.cs & Controller)
Service & Global Filter Registration (Program.cs)
Register filters in the DI container when they inject scoped or singleton dependencies (such as IIdempotencyStore or ILogger<T>), and apply them globally or per-controller/action via [ServiceFilter(typeof(...))] or [TypeFilter(typeof(...))].
C#
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IIdempotencyStore, InMemoryIdempotencyStore>();
builder.Services.AddScoped<IdempotencyActionFilter>();
builder.Services.AddScoped<ResponseTelemetryResultFilter>();
builder.Services.AddControllersWithViews(options =>
{
// Apply response telemetry result filter globally across MVC actions
options.Filters.AddService<ResponseTelemetryResultFilter>();
});
var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapControllers();
app.Run();
Controller Action Applying [ServiceFilter] (SubmissionsController.cs)
C#
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/submissions")]
public sealed class SubmissionsController : ControllerBase
{
[HttpPost]
[ServiceFilter(typeof(IdempotencyActionFilter))]
public IActionResult Submit([FromBody] SubmitOrderCommand command)
{
if (!ModelState.IsValid)
{
return ValidationProblem(ModelState);
}
var response = new SubmitOrderResponse(
SubmissionId: Guid.NewGuid(),
ReferenceCode: command.ReferenceCode.Trim().ToUpperInvariant(),
Amount: command.Amount,
Currency: command.Currency.Trim().ToUpperInvariant(),
ProcessedAtUtc: DateTimeOffset.UtcNow);
return Ok(response);
}
}
6. End-to-End Integration Testing with WebApplicationFactory<Program>
Testing filters through WebApplicationFactory<Program> verifies header enforcement, short-circuiting, idempotent replay, and response header injection across the real MVC pipeline:
C#
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
public sealed class SubmissionsControllerTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;
public SubmissionsControllerTests(WebApplicationFactory<Program> factory)
{
_factory = factory;
}
[Fact]
public async Task Submit_MissingIdempotencyKey_ReturnsBadRequest400()
{
using HttpClient client = _factory.CreateClient();
var payload = new SubmitOrderCommand("REF-100", 150.00m, "USD");
HttpResponseMessage response = await client.PostAsJsonAsync("/api/submissions", payload);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.True(response.Headers.Contains("X-Trace-Id"));
}
[Fact]
public async Task Submit_SameIdempotencyKeyTwice_ReplaysIdenticalResponse()
{
using HttpClient client = _factory.CreateClient();
string key = $"key-{Guid.NewGuid():N}";
var payload = new SubmitOrderCommand("REF-200", 320.00m, "USD");
using var firstRequest = new HttpRequestMessage(HttpMethod.Post, "/api/submissions")
{
Content = JsonContent.Create(payload)
};
firstRequest.Headers.Add("Idempotency-Key", key);
HttpResponseMessage firstResponse = await client.SendAsync(firstRequest);
Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode);
Assert.False(firstResponse.Headers.Contains("X-Idempotent-Replay"));
SubmitOrderResponse? firstBody = await firstResponse.Content.ReadFromJsonAsync<SubmitOrderResponse>();
Assert.NotNull(firstBody);
using var secondRequest = new HttpRequestMessage(HttpMethod.Post, "/api/submissions")
{
Content = JsonContent.Create(payload)
};
secondRequest.Headers.Add("Idempotency-Key", key);
HttpResponseMessage secondResponse = await client.SendAsync(secondRequest);
Assert.Equal(HttpStatusCode.OK, secondResponse.StatusCode);
Assert.True(secondResponse.Headers.Contains("X-Idempotent-Replay"));
SubmitOrderResponse? secondBody = await secondResponse.Content.ReadFromJsonAsync<SubmitOrderResponse>();
Assert.NotNull(secondBody);
Assert.Equal(firstBody.SubmissionId, secondBody.SubmissionId);
}
}
7. Conclusion
IAsyncActionFilter and IAsyncResultFilter give ASP.NET Core MVC applications a clean, DI-friendly way to enforce cross-cutting rules—such as idempotency keys, action auditing, and response telemetry headers—right inside the MVC action and result lifecycle. By keeping those concerns in composable async filters and resolving them via ServiceFilter or global MvcOptions registration, your controller actions stay focused on domain orchestration while every endpoint behaves consistently across retries and responses.
Join the conversation! Your thoughts help the community grow.