DKNet.AspCore.Idempotency 10.1.17

There is a newer version of this package available.
See the version list below for details.
dotnet add package DKNet.AspCore.Idempotency --version 10.1.17
                    
NuGet\Install-Package DKNet.AspCore.Idempotency -Version 10.1.17
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="DKNet.AspCore.Idempotency" Version="10.1.17" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="DKNet.AspCore.Idempotency" Version="10.1.17" />
                    
Directory.Packages.props
<PackageReference Include="DKNet.AspCore.Idempotency" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add DKNet.AspCore.Idempotency --version 10.1.17
                    
#r "nuget: DKNet.AspCore.Idempotency, 10.1.17"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package DKNet.AspCore.Idempotency@10.1.17
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=DKNet.AspCore.Idempotency&version=10.1.17
                    
Install as a Cake Addin
#tool nuget:?package=DKNet.AspCore.Idempotency&version=10.1.17
                    
Install as a Cake Tool

DKNet.AspCore.Idempotency

NuGet License: MIT

An ASP.NET Core minimal-API endpoint filter that makes mutating endpoints safe to retry: requests carrying the same idempotency key are processed once, with duplicates either rejected with 409 Conflict or replayed from cache.

Features

  • Endpoint filter (RequiredIdempotentKey()) that enforces an idempotency key on any minimal API route
  • Group-level declaration — the same RequiredIdempotentKey() on a RouteGroupBuilder covers every POST endpoint in the group (verb set overridable), nested groups and later-added endpoints included
  • Composite key validation (presence, length, format) with automatic 400 Bad Request responses
  • Two duplicate-request strategies: 409 Conflict (default) or transparent cached-response replay
  • Caller scope isolation (authenticated user, HMAC'd Authorization header, or client IP) so the same key from different callers never collides — or supply your own resolver
  • Pluggable storage via IIdempotencyKeyStore, with a built-in IDistributedCache-backed store out of the box
  • Configurable which HTTP status codes get cached, cache key prefix, and result expiration

Installation

dotnet add package DKNet.AspCore.Idempotency

Quick Start

using DKNet.AspCore.Idempotency;

var builder = WebApplication.CreateBuilder(args);

// This package supplies the endpoint filter and options; it does not ship a usable store.
// Reference one of the store packages and call its registration extension:
//   DKNet.AspCore.Idempotency.MsSqlStore   -> AddIdempotencyWithMsSqlStore(connectionString)
//   DKNet.AspCore.Idempotency.NpgsqlStore  -> AddIdempotencyWithNpgsqlStore(connectionString)
//   DKNet.AspCore.Idempotency.RedisStore   -> AddIdempotencyWithRedisStore(connectionString)
// All three reserve the key atomically. To use a store of your own, implement
// IIdempotencyKeyStore and register it with AddIdempotentKey<TStore>().
builder.Services.AddIdempotencyWithMsSqlStore(
    builder.Configuration.GetConnectionString("Idempotency")!);

var app = builder.Build();

app.MapPost("/orders", CreateOrder)
    .RequiredIdempotentKey();

await app.RunAsync();

Clients call POST /orders with an X-Idempotency-Key header; a retried request with the same key never re-executes CreateOrder.

For multi-instance production traffic, swap the built-in store for an atomic one from the ecosystem — DKNet.AspCore.Idempotency.MsSqlStore, DKNet.AspCore.Idempotency.NpgsqlStore, or DKNet.AspCore.Idempotency.RedisStore — each of which ships its own AddIdempotencyWithXxxStore(...) registration. AddIdempotentKey<TStore>(...) is for a public IIdempotencyKeyStore you write yourself; every shipped store type is internal.

Group-level declaration

RequiredIdempotentKey() also extends RouteGroupBuilder, so a single declaration on a group protects every matching endpoint in it — including endpoints added to that group later, and endpoints of groups nested under it:

var orders = app.MapGroup("/api/orders").RequiredIdempotentKey();                 // POST endpoints only
var admin  = app.MapGroup("/api/admin").RequiredIdempotentKey("POST", "DELETE");  // explicit verb set

orders.MapPost("/", CreateOrder);            // protected — no per-endpoint call needed
orders.MapGet("/{id}", GetOrder);            // untouched: no header required, no duplicate lookup
orders.MapGroup("/{id}/lines")               // nested group inherits the same verb selection
      .MapPost("/", AddOrderLine);           // protected

The default covered set is POST only — PUT and DELETE are already idempotent by HTTP semantics, so they are opt-in through the verb arguments. Verbs are matched case-insensitively against each endpoint's routed verb, and coverage is decided once at application start: nothing the caller sends (an X-HTTP-Method-Override header included) can move an endpoint into or out of coverage.

An endpoint whose verb falls outside the set is left completely alone — no header requirement, no rejection, no duplicate lookup, nothing retained — so reads keep working for clients that never send a key. A covered endpoint behaves exactly like an individually declared one: same header name, key validation, duplicate handling and retention, all still driven by IdempotencyOptions. The per-endpoint overload is unchanged, and an endpoint covered both ways is still protected exactly once.

Two limits worth knowing:

  • An endpoint registered without a verb constraint (app.Map(...), which also serves GET) has no routed verb to match and is not covered. Declare explicit verbs (MapPost, MapPut, ...) on endpoints you want protected.
  • A verb set that omits a state-changing endpoint leaves that endpoint unprotected. That is an explicit choice — a group protects only the verbs you name.

Customisation reference

All configuration lives on IdempotencyOptions, passed as the Action<IdempotencyOptions> on AddIdempotentKey<TStore>() (and on every store package's AddIdempotencyWithXxxStore(...)). Values are validated eagerly at registration — an empty header key or cache prefix, a non-positive expiration, a status-code window outside 100–599 or with min above max, a null JsonSerializerOptions, a MaxIdempotencyKeyLength below 1, an empty key pattern, or a whitespace ScopeHmacSecret each throw ArgumentException immediately rather than failing at request time.

Knob Type Default Effect
IdempotencyHeaderKey string "X-Idempotency-Key" Request header the filter reads the key from.
IdempotencyKeyPattern string ^[a-zA-Z0-9\-_]+$ Regex a key must match; a mismatch is 400 Bad Request.
MaxIdempotencyKeyLength int 255 Longer keys are rejected with 400.
ConflictHandling IdempotentConflictHandling ConflictResponse ConflictResponse answers a duplicate with 409; CachedResult replays the original status, body and content type.
Expiration TimeSpan 4 hours Absolute lifetime of a cached result before the key is treated as new again.
InFlightReservationTimeout TimeSpan 30 seconds How long the in-flight reservation placeholder blocks a retry before it can be reclaimed.
MinStatusCodeForCaching int 200 Inclusive lower bound of the cacheable status range. Must be ≥ 100.
MaxStatusCodeForCaching int 299 Inclusive upper bound. Must be ≤ 599 and ≥ the minimum.
AdditionalCacheableStatusCodes HashSet<int> (get-only, mutable) empty Extra status codes cached outside the min/max window.
CachePrefix string "idem" Prepended, unchanged, to every storage key.
JsonSerializerOptions JsonSerializerOptions camelCase naming policy Used to serialize and deserialize the cached response body.
KeyScopeResolver Func<HttpContext, string?>? null Custom caller-scope resolver. When set it is used verbatim and the default chain is skipped entirely; returning null yields an empty scope.
ScopeHmacSecret string? null Enables the Authorization-header HMAC-SHA256 fallback in the default scope chain. Only the digest is ever used or logged.
IncludeClientIpInScope bool false Enables the client-IP fallback in the default scope chain.

The default caller-scope chain, used when KeyScopeResolver is null: authenticated user's ClaimTypes.NameIdentifieruser:{id}; else HMAC of the Authorization header when ScopeHmacSecret is set → auth:{hex}; else the remote IP when IncludeClientIpInScope is trueip:{address}; else the empty string.

Extension point — IIdempotencyKeyStore

public interface IIdempotencyKeyStore
{
    ValueTask<(bool processed, CachedResponse? response)> IsKeyProcessedAsync(IdempotentKeyInfo keyInfo);
    ValueTask MarkKeyAsProcessedAsync(IdempotentKeyInfo keyInfo, CachedResponse cachedResponse);
}

IsKeyProcessedAsync must check and reserve atomically: returning (false, null) has to have already recorded the key as in flight, so no concurrent caller for the same key can also observe (false, null). The reservation must be distinguishable from a completed response (every shipped store uses HTTP 102 as the sentinel) and must expire after InFlightReservationTimeout so a crashed handler cannot block the key forever. Get that wrong and duplicate requests both run the handler, which is the one thing this package exists to prevent.

Migration — namespace changes in this release

Root types were grouped into concern folders; the namespace of each moved type now ends with its folder name. This is an import-only source break: no type was renamed, removed, resignatured, or had its behaviour changed — update the using line and you're done.

Type Old namespace New namespace
IdempotencyEndpointFilter (incl. RequiredIdempotentKey()), IdempotencyKeyScopeResolver, IdempotentKeyInfo DKNet.AspCore.Idempotency DKNet.AspCore.Idempotency.Filtering
CachedResponse DKNet.AspCore.Idempotency DKNet.AspCore.Idempotency.Store (joins the existing IIdempotencyKeyStore/IdempotencyDistributedCacheStore)

IdempotencySetup (registration point) and IdempotencyOptions/IdempotentConflictHandling (the configuration surface) stay at DKNet.AspCore.Idempotency.

Documentation

Full feature guide, configuration reference, and store comparison: https://github.com/baoduy/DKNet/blob/main/docs/AspNetCore/DKNet.AspCore.Idempotency.md

License

MIT — see LICENSE.

About

Developed by Steven Hoang.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (4)

Showing the top 4 NuGet packages that depend on DKNet.AspCore.Idempotency:

Package Downloads
DKNet.AspCore.Idempotency.MsSqlStore

DKNet is an enterprise-grade .NET library collection focused on advanced EF Core extensions, dynamic predicate building, and the Specification pattern. It provides production-ready tools for building robust, type-safe, and testable data access layers, including dynamic LINQ support, LinqKit integration. Designed for modern cloud-native applications, DKNet enforces strict code quality, async best practices, and full documentation for all public APIs. Enterprise-grade .NET library suite for modern application development, featuring advanced EF Core extensions (dynamic predicates, specifications, LinqKit), robust Domain-Driven Design (DDD) patterns, and domain event support. DKNet empowers scalable, maintainable, and testable solutions with type-safe validation, async/await, XML documentation, and high code quality standards. Ideal for cloud-native, microservices, and enterprise architectures.

DKNet.AspCore.Idempotency.NpgsqlStore

DKNet is an enterprise-grade .NET library collection focused on advanced EF Core extensions, dynamic predicate building, and the Specification pattern. It provides production-ready tools for building robust, type-safe, and testable data access layers, including dynamic LINQ support, LinqKit integration. Designed for modern cloud-native applications, DKNet enforces strict code quality, async best practices, and full documentation for all public APIs. Enterprise-grade .NET library suite for modern application development, featuring advanced EF Core extensions (dynamic predicates, specifications, LinqKit), robust Domain-Driven Design (DDD) patterns, and domain event support. DKNet empowers scalable, maintainable, and testable solutions with type-safe validation, async/await, XML documentation, and high code quality standards. Ideal for cloud-native, microservices, and enterprise architectures.

DKNet.AspCore.Idempotency.RedisStore

DKNet is an enterprise-grade .NET library collection focused on advanced EF Core extensions, dynamic predicate building, and the Specification pattern. It provides production-ready tools for building robust, type-safe, and testable data access layers, including dynamic LINQ support, LinqKit integration. Designed for modern cloud-native applications, DKNet enforces strict code quality, async best practices, and full documentation for all public APIs. Enterprise-grade .NET library suite for modern application development, featuring advanced EF Core extensions (dynamic predicates, specifications, LinqKit), robust Domain-Driven Design (DDD) patterns, and domain event support. DKNet empowers scalable, maintainable, and testable solutions with type-safe validation, async/await, XML documentation, and high code quality standards. Ideal for cloud-native, microservices, and enterprise architectures.

DKNet.AspCore.Idempotency.Relational

DKNet is an enterprise-grade .NET library collection focused on advanced EF Core extensions, dynamic predicate building, and the Specification pattern. It provides production-ready tools for building robust, type-safe, and testable data access layers, including dynamic LINQ support, LinqKit integration. Designed for modern cloud-native applications, DKNet enforces strict code quality, async best practices, and full documentation for all public APIs. Enterprise-grade .NET library suite for modern application development, featuring advanced EF Core extensions (dynamic predicates, specifications, LinqKit), robust Domain-Driven Design (DDD) patterns, and domain event support. DKNet empowers scalable, maintainable, and testable solutions with type-safe validation, async/await, XML documentation, and high code quality standards. Ideal for cloud-native, microservices, and enterprise architectures.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
10.1.19 40 9/3/2026
10.1.18 40 9/3/2026
10.1.17 40 9/3/2026
10.1.16 50 9/3/2026
10.1.15 72 9/1/2026
10.1.14 71 9/1/2026
10.1.13 88 8/31/2026
10.1.12 134 8/25/2026
10.1.11 131 8/24/2026
10.1.10 142 8/22/2026
10.1.9 161 8/22/2026
10.1.8 129 8/21/2026
10.1.7 159 8/21/2026
10.1.6 135 8/21/2026
10.1.5 128 8/20/2026
10.1.4 123 8/20/2026
10.1.3 124 8/19/2026
10.1.2 126 8/19/2026
10.1.1 122 8/19/2026
10.0.36 133 8/18/2026
Loading failed