TL.MiddlewareLibrary 0.5.0

dotnet add package TL.MiddlewareLibrary --version 0.5.0
                    
NuGet\Install-Package TL.MiddlewareLibrary -Version 0.5.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="TL.MiddlewareLibrary" Version="0.5.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="TL.MiddlewareLibrary" Version="0.5.0" />
                    
Directory.Packages.props
<PackageReference Include="TL.MiddlewareLibrary" />
                    
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 TL.MiddlewareLibrary --version 0.5.0
                    
#r "nuget: TL.MiddlewareLibrary, 0.5.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 TL.MiddlewareLibrary@0.5.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=TL.MiddlewareLibrary&version=0.5.0
                    
Install as a Cake Addin
#tool nuget:?package=TL.MiddlewareLibrary&version=0.5.0
                    
Install as a Cake Tool

🚀 TL.MiddlewareLibrary

.NET License: MIT

Suíte modular de middlewares para ASP.NET Core (.NET 8 e .NET 9): diagnóstico de latência com zero alocação, controle de taxa por IP, cache em memória com pooling e respostas estruturadas de erro no padrão RFC 7807 (ProblemDetails) integradas a TL.BaseContracts.

O TL.MiddlewareLibrary é uma biblioteca de infraestrutura transversal para o pipeline HTTP do ASP.NET Core, concebida para simplificar o desenvolvimento de APIs modernas, eliminar código defensivo repetitivo em controllers/endpoints e padronizar o tratamento de exceções de negócio e falhas não tratadas.


📦 Instalação

Adicione o pacote via .NET CLI:

dotnet add package TL.MiddlewareLibrary

🚀 Métodos de Extensão do Pipeline

Extensão Middleware Descrição Resumida
app.UseRequestTiming() RequestTimingMiddleware Mede a latência da requisição com zero alocação e injeta o header X-Response-Time-Ms.
app.UseRequestResponseLogging() RequestResponseLoggingMiddleware Auditoria segura de requisições e respostas HTTP com sanitização AppSec CWE-532.
app.UseRateLimiting(options) RateLimitingMiddleware Protege a API via Token Bucket nativo (.NET 8/9), bypass de IPs/CIDRs e header Retry-After.
app.UseIdempotency(options) IdempotencyMiddleware Cache transparente para requisições mutantes (Idempotency-Key) com header X-Cache-Lookup.
app.UseAuthenticationMiddleware() AuthenticationMiddleware Validação ágil de cabeçalho Authorization no início do fluxo.
app.UseCachingMiddleware(duration) CachingMiddleware Cache em memória transparente para requisições GET e HEAD (200 OK) com chave composta e pooling de buffers.
app.UseExceptionHandling() / app.UseGlobalExceptionHandling() ExceptionHandlingMiddleware Captura global de exceções imprevistas, gerando resposta RFC 7807 amigável com traceId e X-Correlation-Id.
app.UseStatusCodeMiddleware() StatusCodeMiddleware Mapeia exceções de domínio tipadas e contratos de erro (Error, ValidationError de TL.BaseContracts).

💡 Exemplo Rápido de Uso

using TL.MiddlewareLibrary.Exceptions;
using TL.MiddlewareLibrary.Extensions;
using TL.MiddlewareLibrary.Middlewares;
using TL.BaseContracts;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMemoryCache();

var app = builder.Build();

app.UseRequestTiming();
app.UseRequestResponseLogging();
app.UseRateLimiting(new RateLimitingOptions
{
    PermitLimit = 100,
    Period = TimeSpan.FromMinutes(1),
    WhiteListIps = { "127.0.0.1", "10.0.0.0/8" }
});
app.UseIdempotency();
app.UseCachingMiddleware(TimeSpan.FromMinutes(2));
app.UseExceptionHandling();
app.UseStatusCodeMiddleware();

app.MapGet("/api/clientes/{id}", (int id) =>
{
    if (id <= 0)
        throw new BadRequestException("O ID informado é inválido.");

    return Results.Ok(new { id, nome = "Cliente Exemplo" });
});

app.Run();

🎯 Ergonomia Minimal APIs (ToHttpResult())

Elimine o código defensivo repetitivo de pattern matching nas Minimal APIs com a bridge ToHttpResult():

using TL.BaseContracts.Http;

app.MapGet("/api/pedidos/{id:guid}", (Guid id, PedidoService service) =>
{
    return service.ObterPorId(id).ToHttpResult();
});

app.MapPost("/api/pedidos", async (NovoPedidoRequest request, PedidoService service) =>
{
    var result = await service.CriarPedidoAsync(request);
    return result.ToHttpResult(pedido => Results.Created($"/api/pedidos/{pedido.Id}", pedido));
});

Erros são mapeados automaticamente para RFC 7807 (ProblemDetails e ValidationProblemDetails).


👤 Injeção de Identidade e Tenant (ICurrentUser e ICurrentTenant)

Registre as implementações integradas ao IHttpContextAccessor:

using TL.MiddlewareLibrary.Context;

builder.Services.AddCurrentUser();
builder.Services.AddCurrentTenant(headerName: "X-Tenant-Id");

Permite injetar ICurrentUser e ICurrentTenant diretamente nos serviços de aplicação.


📄 Licença

Distribuído sob a licença MIT.

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 is compatible.  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
0.5.0 106 9/28/2026
0.4.0 89 9/25/2026
0.3.1 100 9/22/2026
0.3.0 102 9/18/2026
0.2.0 114 9/11/2026
0.1.1 114 9/7/2026
0.1.0 108 9/7/2026
0.0.1-beta.2 89 8/28/2026