In production ASP.NET Core MVC applications handling payments, orders, or mutating commands, two operational failure modes surface repeatedly:

  1. Duplicate Mutations on Retry: Clients, mobile apps, or reverse proxies retry timed-out or uncertain POST/PUT/PATCH requests. Without an idempotency key guard, retrying a payment or state transition risks executing the side effect twice.

  2. 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, or 500, 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

VB.NET
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

IAsyncActionFilter

Checks Idempotency-Key header on mutating actions, replays prior 2xx ObjectResult payloads, or runs await next() and caches the result.

Never caches failed (4xx/5xx) or non-ObjectResult responses as completed replays; normalizes/hashes the key safely.

IAsyncResultFilter

Measures result execution latency, records HTTP status/result type, and adds diagnostic response headers prior to response start.

Sets headers while HttpResponse.HasStarted is false so Kestrel/reverse proxies never throw header-after-start errors.

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#

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);
            }
        }
    }
}

3. Response Telemetry IAsyncResultFilter Implementation

Now let's create a ResponseTelemetryResultFilter (IAsyncResultFilter) that measures how long the action result takes to execute, records the result type and status code via structured logging, and attaches X-Result-Execution-Ms and X-Result-Type headers before the response body starts streaming.

C#

C#
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc.Filters;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public sealed class TrackResponseTelemetryAttribute : Attribute, IFilterFactory
{
    public bool IsReusable => true;

    public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
    {
        var logger = serviceProvider.GetRequiredService<ILogger<ResponseTelemetryResultFilter>>();
        return new ResponseTelemetryResultFilter(logger);
    }
}

public sealed class ResponseTelemetryResultFilter : IAsyncResultFilter
{
    private readonly ILogger<ResponseTelemetryResultFilter> _logger;

    public ResponseTelemetryResultFilter(ILogger<ResponseTelemetryResultFilter> logger)
    {
        _logger = logger;
    }

    public async Task OnResultExecutionAsync(
        ResultExecutingContext context,
        ResultExecutionDelegate next)
    {
        ArgumentNullException.ThrowIfNull(context);
        ArgumentNullException.ThrowIfNull(next);

        string resultTypeName = context.Result?.GetType().Name ?? "EmptyResult";
        long startTicks = Stopwatch.GetTimestamp();

        if (!context.HttpContext.Response.HasStarted)
        {
            context.HttpContext.Response.Headers["X-Result-Type"] = resultTypeName;
        }

        ResultExecutedContext executedContext = await next();

        double elapsedMs = Stopwatch.GetElapsedTime(startTicks).TotalMilliseconds;
        int statusCode = executedContext.HttpContext.Response.StatusCode;

        if (!executedContext.HttpContext.Response.HasStarted)
        {
            context.HttpContext.Response.Headers["X-Result-Execution-Ms"] =
                elapsedMs.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture);
        }

        _logger.LogInformation(
            "MVC result {ResultType} finished with HTTP {StatusCode} in {ElapsedMs:0.00} ms on {Path} (Canceled: {Canceled}).",
            resultTypeName,
            statusCode,
            elapsedMs,
            context.HttpContext.Request.Path,
            executedContext.Canceled);
    }
}

4. MVC Controller and Program.cs Wiring

Let's wire a PaymentsController with [IdempotentMutation(ttlMinutes: 60)] and [TrackResponseTelemetry] so repeated POST /api/payments/charge calls carrying the same Idempotency-Key return the exact same charge reference and ExecutionCount without double-charging.

Controller (PaymentsController.cs)

C#

C#
using System.Collections.Concurrent;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;

public sealed record ChargePaymentRequest(
    [Required] string OrderId,
    [Range(0.01, 1_000_000.00)] decimal Amount,
    [Required, MinLength(3), MaxLength(3)] string Currency
);

public sealed record ChargePaymentResponse(
    string TransactionId,
    string OrderId,
    decimal Amount,
    string Currency,
    int LedgerChargeCount,
    DateTimeOffset ProcessedAtUtc
);

public sealed class PaymentLedgerService
{
    private readonly ConcurrentDictionary<string, ChargePaymentResponse> _chargesByKey = new(StringComparer.Ordinal);
    private int _ledgerChargeCount;

    public ChargePaymentResponse ChargeOnce(string idempotencyKey, ChargePaymentRequest request)
    {
        return _chargesByKey.GetOrAdd(idempotencyKey, _ =>
        {
            int seq = Interlocked.Increment(ref _ledgerChargeCount);
            return new ChargePaymentResponse(
                TransactionId: $"TXN-{seq:0000}-{Guid.NewGuid().ToString("N")[..8].ToUpperInvariant()}",
                OrderId: request.OrderId.Trim().ToUpperInvariant(),
                Amount: decimal.Round(request.Amount, 2, MidpointRounding.AwayFromZero),
                Currency: request.Currency.Trim().ToUpperInvariant(),
                LedgerChargeCount: seq,
                ProcessedAtUtc: DateTimeOffset.UtcNow);
        });
    }
}

[ApiController]
[Route("api/payments")]
[TrackResponseTelemetry]
public sealed class PaymentsController : ControllerBase
{
    private readonly PaymentLedgerService _ledger;

    public PaymentsController(PaymentLedgerService ledger)
    {
        _ledger = ledger;
    }

    [HttpPost("charge")]
    [IdempotentMutation(ttlMinutes: 60)]
    public IActionResult Charge([FromBody] ChargePaymentRequest request)
    {
        if (!ModelState.IsValid)
        {
            return ValidationProblem(ModelState);
        }

        string idempotencyKey = Request.Headers[IdempotentMutationAttribute.HeaderName].ToString().Trim();
        if (string.IsNullOrWhiteSpace(idempotencyKey))
        {
            return BadRequest(new ProblemDetails
            {
                Title = "Missing Idempotency-Key",
                Detail = "The 'Idempotency-Key' header is required for charge requests.",
                Status = StatusCodes.Status400BadRequest
            });
        }

        ChargePaymentResponse result = _ledger.ChargeOnce(idempotencyKey, request);
        return Created($"/api/payments/receipts/{result.TransactionId}", result);
    }
}

Application Setup (Program.cs)

C#

C#
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddMemoryCache();
builder.Services.AddSingleton<IIdempotencyStore, MemoryIdempotencyStore>();
builder.Services.AddSingleton<PaymentLedgerService>();
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 that the first charge creates a transaction with X-Idempotency-Replay: false, a retry with the same Idempotency-Key returns X-Idempotency-Replay: true with the identical TransactionId and LedgerChargeCount, and ResponseTelemetryResultFilter emits X-Result-Type and X-Result-Execution-Ms headers.

C#

C#
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;

public sealed class IdempotencyAndResultTelemetryTests : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly WebApplicationFactory<Program> _factory;

    public IdempotencyAndResultTelemetryTests(WebApplicationFactory<Program> factory)
    {
        _factory = factory;
    }

    [Fact]
    public async Task ChargePayment_RetriedWithSameIdempotencyKey_ReplaysSameTransactionWithoutDoubleCharging()
    {
        using HttpClient client = _factory.CreateClient();
        string idempotencyKey = $"idem-{Guid.NewGuid():N}";
        var payload = new ChargePaymentRequest("ORD-9001", 250.00m, "USD");

        using var firstReq = new HttpRequestMessage(HttpMethod.Post, "/api/payments/charge")
        {
            Content = JsonContent.Create(payload)
        };
        firstReq.Headers.Add(IdempotentMutationAttribute.HeaderName, idempotencyKey);

        HttpResponseMessage firstRes = await client.SendAsync(firstReq);
        Assert.Equal(HttpStatusCode.Created, firstRes.StatusCode);
        Assert.Equal("false", firstRes.Headers.GetValues("X-Idempotency-Replay").Single());
        Assert.True(firstRes.Headers.Contains("X-Result-Type"));
        Assert.True(firstRes.Headers.Contains("X-Result-Execution-Ms"));

        ChargePaymentResponse? firstCharge = await firstRes.Content.ReadFromJsonAsync<ChargePaymentResponse>();
        Assert.NotNull(firstCharge);

        using var retryReq = new HttpRequestMessage(HttpMethod.Post, "/api/payments/charge")
        {
            Content = JsonContent.Create(payload)
        };
        retryReq.Headers.Add(IdempotentMutationAttribute.HeaderName, idempotencyKey);

        HttpResponseMessage retryRes = await client.SendAsync(retryReq);
        Assert.Equal(HttpStatusCode.Created, retryRes.StatusCode);
        Assert.Equal("true", retryRes.Headers.GetValues("X-Idempotency-Replay").Single());

        ChargePaymentResponse? retryCharge = await retryRes.Content.ReadFromJsonAsync<ChargePaymentResponse>();
        Assert.NotNull(retryCharge);

        Assert.Equal(firstCharge.TransactionId, retryCharge.TransactionId);
        Assert.Equal(firstCharge.LedgerChargeCount, retryCharge.LedgerChargeCount);
    }
}

6. Conclusion

Combining IAsyncActionFilter for idempotency-key replay protection with IAsyncResultFilter for result-execution timing and response headers makes mutating ASP.NET Core MVC endpoints resilient against network retries while giving you clear visibility into result execution performance. Keeping replay caching scoped to successful 2xx ObjectResult payloads and writing response headers before HttpResponse.HasStarted ensures safe, predictable behavior in production.