In production ASP.NET Core MVC applications handling payments, orders, or mutating commands, two operational failure modes surface repeatedly:
Duplicate Mutations on Retry: Clients, mobile apps, or reverse proxies retry timed-out or uncertain
POST/PUT/PATCHrequests. Without an idempotency key guard, retrying a payment or state transition risks executing the side effect twice.Blind Response & Serialization Telemetry: Monitoring only request entry or relying solely on generic middleware leaves a gap around MVC action completion and result execution—such as knowing whether an action returned
200,201,400, or500, how long action + result execution took, or whether a response was served as a replay.
Combining IAsyncActionFilter (for idempotency key lookup, in-flight/completed replay, and result persistence on mutating requests) with IAsyncResultFilter (for measuring result/response execution duration, status codes, and attaching response diagnostic headers) keeps controllers clean while making mutations safe under retries and responses observable.
1. Architectural Blueprint & Filter Pipeline Flow
Plaintext
Incoming HTTP Request (e.g., POST /api/payments/charge with Idempotency-Key header)
│
▼
[Routing] ──> [Authorization] ──> [Resource Filters] ──> [Model Binding]
│
▼
┌────────────────────────────────────────────────────────────────────┐
│ 1. IAsyncActionFilter.OnActionExecutionAsync() │
│ • For mutating methods (POST/PUT/PATCH) with Idempotency-Key: │
│ - Already completed? Set context.Result = cached ObjectResult │
│ (marks X-Idempotency-Replay: true & skips action) │
│ - Otherwise execute action via await next() │
│ - On 2xx ObjectResult, store snapshot keyed by Idempotency-Key│
└───────────────────────────────┬────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────────────────┐
│ 2. IAsyncResultFilter.OnResultExecutionAsync() │
│ • Starts high-resolution stopwatch around result execution │
│ • Writes X-Action-Result-Ms & X-Response-Status headers before │
│ result starts writing to response body │
│ • Records structured telemetry & result outcome │
└────────────────────────────────────────────────────────────────────┘
Filter | Responsibility | Key Safeguard |
| Checks | Never caches failed ( |
| Measures result execution latency, records HTTP status/result type, and adds diagnostic response headers prior to response start. | Sets headers while |
2. Idempotency Store and IAsyncActionFilter Implementation
Let's create a thread-safe IIdempotencyStore (backed by IMemoryCache for single-node or easily swapped for a distributed store in multi-node clusters) and an IdempotencyActionFilter (IAsyncActionFilter) that intercepts mutating requests carrying an Idempotency-Key header.
C#
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Memory;
public sealed record IdempotentResponseRecord(
int StatusCode,
object? Payload,
DateTimeOffset StoredAtUtc
);
public interface IIdempotencyStore
{
bool TryGet(string key, out IdempotentResponseRecord? record);
void Set(string key, IdempotentResponseRecord record, TimeSpan ttl);
}
public sealed class MemoryIdempotencyStore : IIdempotencyStore
{
private readonly IMemoryCache _cache;
public MemoryIdempotencyStore(IMemoryCache cache)
{
_cache = cache;
}
public bool TryGet(string key, out IdempotentResponseRecord? record) =>
_cache.TryGetValue(key, out record);
public void Set(string key, IdempotentResponseRecord record, TimeSpan ttl)
{
var options = new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = ttl
};
_cache.Set(key, record, options);
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public sealed class IdempotentMutationAttribute : Attribute, IFilterFactory
{
public const string HeaderName = "Idempotency-Key";
public int TtlMinutes { get; }
public IdempotentMutationAttribute(int ttlMinutes = 30)
{
TtlMinutes = ttlMinutes > 0 ? ttlMinutes : 30;
}
public bool IsReusable => true;
public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
{
var store = serviceProvider.GetRequiredService<IIdempotencyStore>();
var logger = serviceProvider.GetRequiredService<ILogger<IdempotencyActionFilter>>();
return new IdempotencyActionFilter(store, logger, TimeSpan.FromMinutes(TtlMinutes));
}
}
public sealed class IdempotencyActionFilter : IAsyncActionFilter
{
private readonly IIdempotencyStore _store;
private readonly ILogger<IdempotencyActionFilter> _logger;
private readonly TimeSpan _ttl;
public IdempotencyActionFilter(
IIdempotencyStore store,
ILogger<IdempotencyActionFilter> logger,
TimeSpan ttl)
{
_store = store;
_logger = logger;
_ttl = ttl;
}
public async Task OnActionExecutionAsync(
ActionExecutingContext context,
ActionExecutionDelegate next)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(next);
HttpContext httpContext = context.HttpContext;
bool isMutation = HttpMethods.IsPost(httpContext.Request.Method) ||
HttpMethods.IsPut(httpContext.Request.Method) ||
HttpMethods.IsPatch(httpContext.Request.Method);
string rawKey = httpContext.Request.Headers[IdempotentMutationAttribute.HeaderName].ToString().Trim();
if (!isMutation || string.IsNullOrWhiteSpace(rawKey))
{
await next();
return;
}
string compositeKey = $"idemp:{httpContext.Request.Method}:{httpContext.Request.Path.Value?.ToLowerInvariant()}:{rawKey}";
if (_store.TryGet(compositeKey, out IdempotentResponseRecord? existing) && existing is not null)
{
httpContext.Response.Headers["X-Idempotency-Replay"] = "true";
_logger.LogInformation(
"Replaying idempotent response for key '{IdempotencyKey}' on {Path}.",
rawKey,
httpContext.Request.Path);
context.Result = new ObjectResult(existing.Payload)
{
StatusCode = existing.StatusCode
};
return;
}
httpContext.Response.Headers["X-Idempotency-Replay"] = "false";
ActionExecutedContext executedContext = await next();
if (executedContext.Exception is null &&
!executedContext.Canceled &&
executedContext.Result is ObjectResult objectResult)
{
int statusCode = objectResult.StatusCode ?? executedContext.HttpContext.Response.StatusCode;
if (statusCode is >= 200 and < 300)
{
_store.Set(
compositeKey,
new IdempotentResponseRecord(statusCode, objectResult.Value, DateTimeOffset.UtcNow),
_ttl);
}
}
}
}
Join the conversation! Your thoughts help the community grow.