Org Skills

`Program.cs` baseline for an ASP.NET Core 10 API

Supporting material for dotnet-development. Agents load it on demand; it ships inside the skill folder.

RawSource

Verified 2026-09 against https://learn.microsoft.com/en-us/aspnet/core/release-notes/aspnetcore-10.0, https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis/handle-errors and https://learn.microsoft.com/en-us/dotnet/core/resilience/http-resilience.

Copy the shape, not the feature list: delete what the service does not need. Every API here ships in .NET 10; the .NET 8 column of the table at the end says what to replace when the project targets less.

1. Packages

<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
  <PackageReference Include="Microsoft.AspNetCore.OpenApi" />
  <PackageReference Include="Microsoft.Extensions.Http.Resilience" />
  <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" />
</ItemGroup>

Versions live in Directory.Packages.props (§5), not in the project file.

2. Program.cs

OrderDto, PlaceOrder, IOrderQueries, IOrderService, PaymentsClient and OrdersDbContext are the application's own types; the rest is framework.

using System.Net.Http.Headers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;

var builder = WebApplication.CreateBuilder(args);

// --- Errors -----------------------------------------------------------------
builder.Services.AddProblemDetails(options =>
    options.CustomizeProblemDetails = ctx =>
        ctx.ProblemDetails.Extensions["traceId"] = ctx.HttpContext.TraceIdentifier);
builder.Services.AddExceptionHandler<DomainExceptionHandler>();

// --- Validation (.NET 10+) --------------------------------------------------
builder.Services.AddValidation();

// --- Options ----------------------------------------------------------------
builder.Services.AddOptions<PaymentOptions>()
    .BindConfiguration("Payment")
    .ValidateDataAnnotations()
    .ValidateOnStart();

// --- Data -------------------------------------------------------------------
builder.Services.AddDbContext<OrdersDbContext>(o =>
    o.UseNpgsql(builder.Configuration.GetConnectionString("Orders")));

// --- Outbound HTTP ----------------------------------------------------------
builder.Services.AddHttpClient<PaymentsClient>((sp, http) =>
    {
        var options = sp.GetRequiredService<IOptions<PaymentOptions>>().Value;
        http.BaseAddress = new Uri(options.BaseUrl);
        http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    })
    .AddStandardResilienceHandler(options => options.Retry.DisableForUnsafeHttpMethods());

// --- AuthN / AuthZ ----------------------------------------------------------
builder.Services.AddAuthentication().AddJwtBearer();   // binds Authentication:Schemes:Bearer
builder.Services.AddAuthorizationBuilder()
    .SetFallbackPolicy(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build())
    .AddPolicy("orders:write", p => p.RequireClaim("scope", "orders.write"));

// --- Rate limiting ----------------------------------------------------------
builder.Services.AddRateLimiter(options =>
{
    options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
    options.AddFixedWindowLimiter("per-client", o =>
    {
        o.PermitLimit = 100;
        o.Window = TimeSpan.FromMinutes(1);
        o.QueueLimit = 0;
    });
});

builder.Services.AddOpenApi();

var app = builder.Build();

app.UseExceptionHandler();      // parameterless overload requires AddProblemDetails()
app.UseStatusCodePages();
app.UseAuthentication();
app.UseAuthorization();
app.UseRateLimiter();
app.MapOpenApi();                                   // /openapi/v1.json — OpenAPI 3.1
app.MapOpenApi("/openapi/{documentName}.yaml");     // YAML variant, endpoint only

var orders = app.MapGroup("/orders").WithTags("Orders").RequireRateLimiting("per-client");

orders.MapGet("/{id:guid}", async Task<Results<Ok<OrderDto>, NotFound>> (
        Guid id, IOrderQueries queries, CancellationToken ct) =>
    await queries.GetAsync(id, ct) is { } dto ? TypedResults.Ok(dto) : TypedResults.NotFound());

orders.MapPost("/", async Task<Results<Created<OrderDto>, ValidationProblem>> (
        PlaceOrder command, IOrderService service, CancellationToken ct) =>
    {
        var order = await service.PlaceAsync(command, ct);
        return TypedResults.Created($"/orders/{order.Id}", order);
    })
    .RequireAuthorization("orders:write");

app.Run();

app.Run() must come last; endpoint registrations after it never execute.

3. Mapping exceptions to ProblemDetails

One handler per exception family. Return false for anything you do not own, so the next handler (and finally the built-in one) gets a turn.

using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;

public sealed class DomainExceptionHandler(IProblemDetailsService problemDetails) : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(
        HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
    {
        if (exception is not DomainException domain)
        {
            return false;
        }

        httpContext.Response.StatusCode = StatusCodes.Status409Conflict;

        return await problemDetails.TryWriteAsync(new ProblemDetailsContext
        {
            HttpContext = httpContext,
            Exception = exception,
            ProblemDetails =
            {
                Type = "https://errors.example.com/order-conflict",
                Title = "The order cannot be changed in its current state",
                Detail = domain.Message,          // safe, author-written text only
                Status = StatusCodes.Status409Conflict,
            },
        });
    }
}

public sealed class DomainException(string message) : Exception(message);

Never put exception.Message from an infrastructure exception into Detail — connection strings and internal host names leak that way. type URIs are part of the contract; see api-design.

4. Options type

using System.ComponentModel.DataAnnotations;

public sealed class PaymentOptions
{
    [Required, Url]
    public string BaseUrl { get; init; } = string.Empty;

    [Range(1, 120)]
    public int TimeoutSeconds { get; init; } = 30;
}

ValidateOnStart() turns a missing or malformed value into a start-up failure the platform can see, instead of a 500 on the first request that touches it.

5. Directory.Build.props and Directory.Packages.props

<!-- Directory.Build.props -->
<Project>
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <LangVersion>latest</LangVersion>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
    <AnalysisLevel>latest-recommended</AnalysisLevel>
    <NuGetAudit>true</NuGetAudit>
    <NuGetAuditMode>all</NuGetAuditMode>
  </PropertyGroup>
</Project>
<!-- Directory.Packages.props -->
<Project>
  <PropertyGroup>
    <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
    <CentralPackageTransitivePinningEnabled>true</CentralPackageTransitivePinningEnabled>
  </PropertyGroup>
  <ItemGroup>
    <PackageVersion Include="Microsoft.Extensions.Http.Resilience" Version="9.*" />
  </ItemGroup>
</Project>

TreatWarningsAsErrors plus <Nullable>enable</Nullable> is what makes "fix the flow, don't use !" enforceable rather than advisory.

6. What to replace on older targets

Used above Introduced On .NET 8 use instead
AddValidation() / DisableValidation() .NET 10 FluentValidation, or [ApiController] DataAnnotations on controllers
MapOpenApi() / AddOpenApi() .NET 9 Swashbuckle or NSwag
OpenAPI 3.1 output, .yaml endpoint .NET 10 3.0 JSON from the generator above
TypedResults.ServerSentEvents .NET 10 Write text/event-stream to HttpResponse.Body by hand
Generated Program is already public (ASP0027) .NET 10 Add public partial class Program { } at the end of Program.cs
IExceptionHandler, keyed services .NET 8 Exception-handling middleware; hand-rolled factory