ASP.NET Core Interview Question #229
How would you prevent duplicate form submissions or duplicate API operations?
Senior ASP.NET Core Real-World Scenarios Senior Advanced
Quick Interview Answer
For browser forms, the Post/Redirect/Get pattern prevents ordinary refreshes from resubmitting a successful POST, but it does not solve all duplicate-request scenarios.
Detailed Explanation
For browser forms, the Post/Redirect/Get pattern prevents ordinary refreshes from resubmitting a successful POST, but it does not solve all duplicate-request scenarios.
For operations where duplicates have business impact, use an idempotency strategy. A client can send an idempotency key, and the server can atomically record the key and result so repeated requests return the existing outcome rather than execute the operation again. Database uniqueness constraints are also valuable as a final consistency boundary.
The implementation must be concurrency-safe; a simple in-memory βseen keysβ collection is not sufficient for a multi-instance production system.
Code Example
[HttpPost]
public async Task<IActionResult> Create(
[FromHeader(Name = "Idempotency-Key")] string key,
CreateOrderRequest request,
CancellationToken ct)
{
return await _orderService.CreateIdempotentlyAsync(key, request, ct);
}