RequestContext 2.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package RequestContext --version 2.0.0
                    
NuGet\Install-Package RequestContext -Version 2.0.0
                    
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="RequestContext" Version="2.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="RequestContext" Version="2.0.0" />
                    
Directory.Packages.props
<PackageReference Include="RequestContext" />
                    
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 RequestContext --version 2.0.0
                    
#r "nuget: RequestContext, 2.0.0"
                    
#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 RequestContext@2.0.0
                    
#: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=RequestContext&version=2.0.0
                    
Install as a Cake Addin
#tool nuget:?package=RequestContext&version=2.0.0
                    
Install as a Cake Tool

RequestContext

A lightweight .NET 8 package for production-ready request handling in ASP.NET Core APIs.

RequestContext helps you standardize:

  • Correlation IDs for tracing requests across services
  • Idempotency for safe retry of write operations
  • Global exception handling with structured JSON responses
  • Request context access (IRequestContext) from your application services

What this package provides

1) Correlation ID middleware

  • Reads X-Correlation-Id from incoming requests
  • Generates a new correlation id if missing
  • Sets HttpContext.TraceIdentifier
  • Returns the correlation id in response headers
  • Adds logging scope with CorrelationId

Header used: X-Correlation-Id

2) Idempotency middleware

  • Applies only to endpoints marked with [Idempotency]
  • Uses X-Idempotency-Id request header as idempotency key
  • Uses Redis for short-lived lock + cooldown cache
  • Persists idempotency records in your EF Core DbContext
  • Prevents duplicate processing of same key

Header used: X-Idempotency-Id

3) Global exception middleware

  • Catches unhandled exceptions
  • Returns consistent JSON response with status code + trace info
  • Maps common exceptions:
    • ArgumentException400
    • UnauthorizedAccessException401
    • KeyNotFoundException404
    • all others → 500

4) IRequestContext

Inject IRequestContext anywhere to access request metadata:

  • CorrelationId
  • UserName
  • ClientIp
  • UserAgent
  • IsAuthenticated
  • IdempotencyKey (exposed by contract)

Installation

dotnet add package RequestContext

Quick start

1) Register services

using RequestContext.DependancyInjection;
using RequestContext.Extensions;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddHttpContextAccessor();
builder.Services.AddRequestContext();

// Register your DbContext (example)
builder.Services.AddDbContext<AppDbContext>(options =>
{
    // options.UseSqlServer(...);
});

// Register Redis connection multiplexer
builder.Services.AddSingleton<IConnectionMultiplexer>(_ =>
    ConnectionMultiplexer.Connect(builder.Configuration.GetConnectionString("Redis")!));

builder.Services.AddIdempotency(options =>
{
    options.DbContextType = typeof(AppDbContext);
});

2) Add middleware pipeline

using RequestContext.Middlewares;
using RequestContext.Extensions;

var app = builder.Build();

app.UseMiddleware<GlobalExceptionMiddleware>();
app.UseMiddleware<CorrelationIdMiddleware>();
app.UseIdempotency();

app.MapControllers();
app.Run();

Recommended order: GlobalExceptionMiddlewareCorrelationIdMiddlewareUseIdempotency()


Using idempotency on endpoints

Annotate write endpoints with [Idempotency]:

[HttpPost("payments")]
[Idempotency(120)] // key valid for 120 seconds
public IActionResult CreatePayment([FromBody] CreatePaymentRequest request)
{
    // Your write logic
    return Ok(new { success = true });
}

Without expiry (never expires):

[Idempotency]

Client request must include:

X-Idempotency-Id: your-unique-operation-key

Consuming IRequestContext

public class AuditService
{
    private readonly IRequestContext _requestContext;

    public AuditService(IRequestContext requestContext)
    {
        _requestContext = requestContext;
    }

    public void WriteAudit()
    {
        var correlationId = _requestContext.CorrelationId;
        var user = _requestContext.UserName;
        var ip = _requestContext.ClientIp;
        // use metadata in logs/audit trail
    }
}

EF Core model requirements

Your configured DbContext should include IdempotencyRecord:

public class AppDbContext : DbContext
{
    public DbSet<IdempotencyRecord> IdempotencyRecords => Set<IdempotencyRecord>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<IdempotencyRecord>()
            .HasIndex(x => x.Key)
            .IsUnique();
    }
}

Then create/apply migrations.


Expected runtime behavior

  • First request with new idempotency key: request is processed and persisted
  • Concurrent duplicate request: returns 409 Conflict
  • Replayed request within cooldown or existing persisted key: returns 409 Conflict
  • Missing idempotency header: middleware skips idempotency handling
  • Endpoints without [Idempotency]: middleware skips idempotency handling

Notes

  • Package target: .NET 8
  • Requires ASP.NET Core pipeline
  • Requires Redis (StackExchange.Redis) and EF Core for idempotency functionality

License

Use according to your package/repository license.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  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

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
3.1.0 102 6/19/2026 3.1.0 is deprecated because it is no longer maintained.
3.0.0 77 6/19/2026
2.1.1 88 6/18/2026
2.1.0 69 6/18/2026
2.0.1 63 6/18/2026
2.0.0 80 6/18/2026
1.2.0 85 6/18/2026
1.0.0 92 6/10/2026 1.0.0 is deprecated because it has critical bugs.