Skip to content

Repository files navigation

SkyWebFramework.Middleware

NuGet Version GitHub Repository License: MIT .NET

SkyWebFramework.Middleware is an enterprise-grade, high-performance middleware library for ASP.NET Core 8 and .NET 9 applications.

It provides a strongly-typed base configuration system (EasyMiddleware<TConfig>), path filtering, a fluent pipeline builder (EasyMiddlewarePipeline), and 11 out-of-the-box production-ready middlewares including in-memory request deduplication, API Key authentication, rate limiting, security headers, correlation ID tracking, error handling, and performance diagnostics.


πŸ”— Repository & Links


🌟 Key Features

  • πŸ” Request Deduplication (Idempotency): Prevents accidental duplicate execution of HTTP write requests (POST, PUT, PATCH) using unique X-Request-ID headers with TaskCompletionSource async coordination.
  • πŸ›‘οΈ Security Headers Hardening: Injects recommended headers (X-Content-Type-Options, X-Frame-Options, X-XSS-Protection) automatically into outgoing HTTP responses.
  • πŸ”‘ API Key Authentication: Validates requests against configured keys via HTTP headers (X-API-Key) or query parameters.
  • ⏱️ Sliding-Window Rate Limiting: Controls request frequency per client IP or custom identifier (X-Client-ID) with custom limit overrides.
  • ⚠️ Global Exception Mapping: Catches unhandled exceptions and maps them to HTTP status codes (400, 401, 500) with standardized JSON error payloads.
  • 🎯 Correlation ID Tracking: Auto-generates or propagates X-Correlation-ID across HTTP request boundaries for distributed tracing.
  • ⚑ Performance & Slow Request Warnings: Measures execution duration, injects Server-Timing headers, and logs slow request warnings exceeding threshold limits.
  • πŸ—œοΈ Response Compression: Dynamically compresses HTTP responses using GZip for text/JSON payloads exceeding configured size thresholds.
  • πŸ“‹ Request & Response Logging: Logs payloads and headers via ILogger while auto-redacting sensitive headers (Authorization, Cookie).
  • πŸ›‘οΈ Request Payload Validation: Restricts max request body sizes, validates Content-Type headers, and blocks dangerous file upload extensions (.exe, .bat).
  • πŸ›£οΈ Path Filtering: Every middleware supports path inclusion and exclusion rules (IncludePaths, ExcludePaths).
  • 🧩 Fluent Pipeline Builder: Cleanly chain middlewares via app.CreateEasyPipeline().

πŸ“¦ Installation

Install via NuGet Package Manager:

dotnet add package SkyWebFramework.Middleware

Or via Package Manager Console:

Install-Package SkyWebFramework.Middleware

πŸ› οΈ Clone & Build Locally

To clone and build the solution locally:

git clone https://github.com/Skyrunner-Dev-ops/SkyWebFramework.Middleware.git
cd SkyWebFramework.Middleware
dotnet build -c Release

To execute the test suite (27 automated unit and stress tests):

dotnet test

πŸš€ Quick Start

In your ASP.NET Core Program.cs:

using SkyWebFramework.Middleware.Core;
using SkyWebFramework.Middleware.PreBuilt;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// Method 1: Using fluent pipeline builder
app.CreateEasyPipeline()
   .AddErrorHandling(options => options.ShowExceptionDetails = app.Environment.IsDevelopment())
   .AddSecurityHeaders()
   .AddCorrelationId()
   .AddRequestDeduplication(options =>
   {
       options.HeaderName = "X-Request-ID";
       options.DeduplicationWindow = TimeSpan.FromSeconds(10);
   })
   .Build();

// Method 2: Individual middleware registration
app.UseEasyMiddleware<RateLimitingMiddleware, RateLimitingOptions>(options =>
{
    options.RequestsPerMinute = 60;
});

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

πŸ’‘ Middleware Capabilities & Code Examples

1. Request Deduplication (RequestDeduplicationMiddleware)

Prevents double-charging or duplicate order creation when client retries requests due to network blips.

app.UseEasyRequestDeduplication(options =>
{
    options.HeaderName = "X-Request-ID";            // Header identifying the request
    options.DeduplicationWindow = TimeSpan.FromSeconds(10); // Window duration
    options.MaxStoredEntries = 1000;                // Prevent memory bounds
    options.MaxResponseBodySizeBytes = 1024 * 1024; // 1 MB payload limit
    options.CacheFailedResponses = false;           // Retries allowed on 4xx/5xx failures
    options.ExcludePaths = new[] { "/swagger" };
});
  • Behavior: First request executes downstream handler; subsequent requests with the same X-Request-ID within 10s receive replayed responses with X-Request-Deduplicated: true header.

2. API Key Authentication (ApiKeyAuthMiddleware)

app.UseEasyMiddleware<ApiKeyAuthMiddleware, ApiKeyAuthOptions>(options =>
{
    options.HeaderName = "X-API-Key";
    options.ValidApiKeys = new[] { "secret-api-key-123" };
    options.AllowQueryString = true;
    options.IncludePaths = new[] { "/api/protected" };
});

3. Rate Limiting (RateLimitingMiddleware)

app.UseEasyMiddleware<RateLimitingMiddleware, RateLimitingOptions>(options =>
{
    options.RequestsPerMinute = 100;
    options.ClientIdentifierHeader = "X-Client-ID";
    options.CustomLimits = new Dictionary<string, int>
    {
        ["vip-client"] = 500
    };
});

4. Global Error Handling (ErrorHandlingMiddleware)

app.UseEasyErrorHandling(options =>
{
    options.ShowExceptionDetails = app.Environment.IsDevelopment();
    options.ExceptionStatusCodes[typeof(ArgumentException)] = 400;
});

5. Security Headers (SecurityHeadersMiddleware)

app.UseEasySecurityHeaders(options =>
{
    options.Headers["X-Frame-Options"] = "DENY";
    options.Headers["X-Content-Type-Options"] = "nosniff";
});

6. Correlation ID (CorrelationIdMiddleware)

app.UseEasyCorrelationId();
// Downstream handlers can access Context.Items["CorrelationId"] or read response header X-Correlation-ID

7. Performance & Slow Request Tracking (PerformanceMiddleware)

app.UseEasyPerformance(options =>
{
    options.SlowRequestThresholdMs = 500;
    options.LogSlowRequests = true;
});

🀝 Contributing

Contributions are welcome! Please feel free to submit issues or pull requests on GitHub.

  1. Fork the Repository: https://github.com/Skyrunner-Dev-ops/SkyWebFramework.Middleware
  2. Create your Feature Branch: git checkout -b feature/AmazingFeature
  3. Commit your Changes: git commit -m 'Add some AmazingFeature'
  4. Push to the Branch: git push origin feature/AmazingFeature
  5. Open a Pull Request

πŸ“„ License

This project is licensed under the MIT License.

Copyright (c) 2026 Surya Pratap Singh - SkyWebFramework

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages