AlefCarlos.AspNetCoreDefaults 11.0.0

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

AspNetCoreDefaults 🔧

Biblioteca base de convenções e extensões para aplicações ASP.NET Core focadas em Web APIs e serviços: oferece defaults opinativos para telemetria, logging HTTP, health checks, service discovery e configurações de HttpClient.

Objetivo

Fornecer um conjunto pequeno e reutilizável de padrões para serviços, permitindo que equipes iniciem novas APIs com observabilidade, resiliência e endpoints operacionais configurados de forma consistente.

Pacote / dependências relevantes

Baseadas no arquivo de projeto (AlefCarlos.AspNetCoreDefaults.csproj):

  • Microsoft.Extensions.AmbientMetadata.Application (ApplicationMetadata)
  • Microsoft.Extensions.Http.Resilience (resiliência de HttpClient)
  • Microsoft.Extensions.ServiceDiscovery (service discovery)
  • OpenTelemetry.Extensions.Hosting, OpenTelemetry.Instrumentation.*, OpenTelemetry.Exporter.OpenTelemetryProtocol (telemetria)

APIs principais

  • TBuilder AddDefaults<TBuilder>(this TBuilder builder) where TBuilder : IHostApplicationBuilder

    • Registra ApplicationMetadata (bind em ambientmetadata:application, validação em start)
    • Chama AddHttpLoggingDefaults(), ConfigureOpenTelemetry(), AddDefaultHealthChecks() e registra service discovery
    • Configura defaults para HttpClient (resiliência e service discovery)
  • TBuilder AddHttpLoggingDefaults<TBuilder>(this TBuilder builder)

    • Habilita HttpLogging com RequestPropertiesAndHeaders | ResponsePropertiesAndHeaders | Duration
    • CombineLogs = true
    • Registra FilterRequestLoggingInterceptor como IHttpLoggingInterceptor
  • TBuilder ConfigureOpenTelemetry<TBuilder>(this TBuilder builder)

    • Configura logging para incluir mensagem formatada e scopes
    • Adiciona métricas e tracing: AspNetCore, HttpClient e Runtime
    • Exclui rotas de health (/health e /alive) de tracing
    • Chama mecanismo que registra OTLP exporter caso OTEL_EXPORTER_OTLP_ENDPOINT seja definido
  • TBuilder AddDefaultHealthChecks<TBuilder>(this TBuilder builder)

    • Adiciona um health check self marcado com tag live (garante liveness básico)
  • WebApplication MapDefaultEndpoints(this WebApplication app)

    • Mapeia /health (readiness — todos checks)
    • Mapeia /alive (liveness — apenas checks taggeados com live)
    • Mapeia /app-info que retorna ApplicationMetadata (excluído da documentação do OpenAPI via ExcludeFromDescription())

Comportamentos e detalhes técnicos

  • ApplicationMetadata

    • Registrado via AddOptionsWithValidateOnStart<ApplicationMetadata>() e BindConfiguration("ambientmetadata:application").
    • BuildVersion é inferido de AssemblyInformationalVersion → Assembly.Version → fallback 0.1.0+unknown-app.
    • Se OTEL_SERVICE_NAME estiver definido, sobrescreve ApplicationName usado pela instrumentação.
    • EnvironmentName é definido a partir de IHostEnvironment.EnvironmentName.
  • OpenTelemetry

    • Instrumentação padrão: AspNetCore, HttpClient e Runtime
    • Tracing omite health endpoints para reduzir ruído
    • Se OTEL_EXPORTER_OTLP_ENDPOINT estiver presente, registra o exporter OTLP automaticamente
  • HttpLogging e interceptor

    • O interceptor FilterRequestLoggingInterceptor remove logging (HttpLoggingFields.None) para endpoints comuns sensíveis/ruidosos: /metrics, /env, /health, /alive, /docs, /swagger.
    • CombineLogs = true ativa logs combinados por request/response
  • HttpClient defaults

    • Ao configurar clientes HTTP via helper interno, é aplicada resiliência padrão (AddStandardResilienceHandler) e integração com service discovery (AddServiceDiscovery).

Exemplo de uso (Program.cs)

var builder = WebApplication.CreateBuilder(args);

// Registra defaults opinativos (telemetria, logging, health checks, service discovery)
builder.AddDefaults();

var app = builder.Build();

// Use o middleware de logging HTTP conforme necessário
app.UseHttpLogging();

// Mapear endpoints operacionais
app.MapDefaultEndpoints();

app.Run();

Variáveis de ambiente e configuração

  • OTEL_SERVICE_NAME — (opcional) define o nome do serviço para OpenTelemetry
  • OTEL_EXPORTER_OTLP_ENDPOINT — (opcional) se definido, habilita o OTLP exporter
  • Configuração de ambientmetadata:application pode fornecer ApplicationName, BuildVersion, etc.

Boas práticas e recomendações

  • Mantenha /app-info protegida em ambientes públicos se retornar dados sensíveis.
  • Controle HttpLogging por ambiente e níveis de log para evitar vazamento de dados em produção.
  • Teste instrumentação e exporters (OTLP) em staging antes de habilitar em produção.
  • Para cenários avançados, estenda AddDefaults() em sua aplicação para inserir checks, middlewares ou exportadores adicionais.

Exemplos & testes

  • Veja samples/webapi-default.cs para uso integrado com AddWebApiDefaults() (apenas um nível acima, mas demonstra AddDefaults() em ação).
Product Compatible and additional computed target framework versions.
.NET net11.0 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on AlefCarlos.AspNetCoreDefaults:

Package Downloads
AlefCarlos.AspNetCoreDefaults.WebApi

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
11.0.0 0 11/19/2026
1.1.8 129 10/27/2026
1.1.7 1,127 8/19/2026
1.1.6 163 7/30/2026
1.1.5 215 6/2/2026
1.1.4 178 6/1/2026
1.1.3 177 5/31/2026
1.1.2 183 5/29/2026
1.1.1 165 5/28/2026
1.1.0 178 5/28/2026
1.0.4 412 5/21/2026
1.0.3 187 4/25/2026
1.0.2 169 4/16/2026
1.0.1 260 12/26/2025
1.0.0 245 12/24/2025
0.0.1-rc8 253 12/24/2025
0.0.1-rc7 257 12/24/2025
0.0.1-rc6 257 12/24/2025