AlefCarlos.AspNetCoreDefaults.WebApi.All 1.0.0

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

AspNetCoreDefaults.WebApi.All 🔧

Biblioteca de convenções e extensões para padronizar Web APIs ASP.NET Core (OpenAPI, ProblemDetails, health checks, logging e OpenTelemetry).

Objetivo

Fornecer um conjunto mínimo e opinativo de defaults para projetos Web API, facilitando:

  • padronização de endpoints (health, alive, app-info)
  • integração e configuração de OpenAPI (via Microsoft.AspNetCore.OpenApi + Scalar.AspNetCore)
  • tratamento de erros com ProblemDetails
  • configuração de logging HTTP e filtros para endpoints sensíveis
  • instrumentação OpenTelemetry (tracing e métricas)

APIs principais

  • WebApplicationBuilder AddWebApiDefaults(this WebApplicationBuilder builder)

    • chama AddDefaults() (telemetria, health checks, logging, service discovery)
    • adiciona ProblemDetails
    • registra OpenApiInfo a partir de ApplicationMetadata
    • registra transformadores de OpenAPI (OpenApiInfoTransformer)
  • void UseProblemDetailsWithDefaults(this WebApplication app)

    • configura UseExceptionHandler() e UseStatusCodePages()
    • habilita UseDeveloperExceptionPage() em Development
  • WebApplication MapDefaultWebApiEndpoints(this WebApplication app)

    • mapeia endpoints padrão: /health, /alive, /app-info
    • mapeia OpenAPI (MapOpenApi()) e referência de API (MapScalarApiReference("/docs"))
  • WebApplication MapDefaultEndpoints(this WebApplication app) (do pacote base)

    • configuração de health checks:
      • /health → readiness (todos checks)
      • /alive → liveness (apenas checks com tag "live")
    • GET /app-info → retorna ApplicationMetadata (excluído da documentação via ExcludeFromDescription())

Exemplo rápido (Program.cs)

var builder = WebApplication.CreateBuilder(args);

// Configura defaults opinativos para WebApi (telemetria, logging, health checks, OpenAPI)
builder.AddWebApiDefaults();

// Personalize OpenAPI se desejar
builder.Services.Configure<OpenApiInfo>(opts => opts.Description = "Descrição detalhada da API");

var app = builder.Build();

app.UseHttpLogging();
app.UseProblemDetailsWithDefaults();

app.MapGet("/", () => new { Message = "Hello, World!" }).WithName("HelloWorld");

// Mapeia endpoints padrão + OpenAPI + docs
app.MapDefaultWebApiEndpoints();

app.Run();

Padrão Result

Este projeto adota o Result Pattern usando a biblioteca Ardalis.Result (e o pacote Ardalis.Result.AspNetCore) para padronizar retornos de operações e facilitar a tradução para respostas HTTP sem lançar exceções para fluxos esperados.

Por que usar ✅

  • Evita o uso excessivo de exceções para fluxos esperados (ex.: não encontrado, validação).
  • Torna o comportamento das APIs previsível e testável.
  • Facilita mapeamento consistente para códigos HTTP, body de erro (ProblemDetails) e documentação (Swagger/OpenAPI).

Integração no projeto 🔧

  • Já incluímos Ardalis.Result e Ardalis.Result.AspNetCore nas dependências (veja Directory.Packages.props / metapacote).
  • Para Minimal APIs utilize ToMinimalApiResult(); para controllers use [TranslateResultToActionResult] ou ToActionResult().

Exemplos (baseados no sample Todo) 💡

Minimal API endpoint (exemplo simplificado):

app.MapPost("/todos", async (IMediator mediator, CreateTodoRequest request) =>
{
    var result = await mediator.Send(new CreateTodoCommand(request.Name));
    return result.ToMinimalApiResult();
});

Handler (use case) retornando Result:

public class CreateTodoHandler : ICommandHandler<CreateTodoCommand, Result>
{
    public async ValueTask<Result> Handle(CreateTodoCommand command, CancellationToken cancellationToken)
    {
        // lógica de criação
        return Result.Success();
    }
}
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

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
1.0.1 188 12/26/2025
1.0.0 188 12/24/2025
0.0.1-rc8 181 12/24/2025
0.0.1-rc7 174 12/24/2025
0.0.1-rc6 180 12/24/2025