LagomEndpoints 0.0.3
See the version list below for details.
dotnet add package LagomEndpoints --version 0.0.3
NuGet\Install-Package LagomEndpoints -Version 0.0.3
<PackageReference Include="LagomEndpoints" Version="0.0.3" />
<PackageVersion Include="LagomEndpoints" Version="0.0.3" />
<PackageReference Include="LagomEndpoints" />
paket add LagomEndpoints --version 0.0.3
#r "nuget: LagomEndpoints, 0.0.3"
#:package LagomEndpoints@0.0.3
#addin nuget:?package=LagomEndpoints&version=0.0.3
#tool nuget:?package=LagomEndpoints&version=0.0.3
LagomEndpoints
One class per endpoint, constructor injection, and a source generator that writes the binding and the registration at build time. No reflection at startup, and it publishes with Native AOT.
// GetOrder.cs
public sealed record GetOrderRequest
{
public Guid Id { get; init; } // route, matched by name
public bool IncludeLines { get; init; } // query
}
public sealed record GetOrderResponse(Guid Id, string Customer);
[Get("/orders/{id:guid}")]
public sealed partial class GetOrder(OrderStore orders)
: ILagomEndpoint<GetOrderRequest, Results<Ok<GetOrderResponse>, NotFound>>
{
public ValueTask<Results<Ok<GetOrderResponse>, NotFound>> HandleAsync(GetOrderRequest request, CancellationToken ct) => ...
}
builder.Services.AddShopApiLagomEndpoints(); // generated: AddScoped for every endpoint
app.MapShopApiLagomEndpoints(); // generated: maps every endpoint
Status: M0 spike
Works today:
[Get],[Post],[Put],[Patch],[Delete],[Endpoint("HEAD", ...)], several per class.ILagomEndpoint<TResult>andILagomEndpoint<TRequest, TResult>. Implementing one of them is what makes a class an endpoint; the route attribute says where it is mapped and is required. Route attributes are not inherited, so every concrete endpoint class needs its own. Endpoints aresealed partialclasses:partialbecause LagomEndpoints generates result helpers into each endpoint class (they arrive in M2; requiringpartialnow means endpoints written today keep compiling then), so the class and every type that contains it must be partial (LAGOM011).- Binding from route, query and headers for strings, anything
IParsable<T>, enums and their nullable forms.[FromRoute],[FromQuery]and[FromHeader]override the default source and name. - JSON body binding for POST, PUT and PATCH: the request object is read from the body with the app's HTTP JSON options, then route, query and header values are applied on top. Positional records work here.
- Binding failures return a 400
application/problem+jsonlisting every error. A body that is not JSON returns 415. - Diagnostics LAGOM001 to LAGOM008 from an analyzer, for endpoints the generator cannot generate code for. The generator and the analyzer share one parser, so they always agree on which endpoints are valid.
- LAGOM009 (warning) for JSON types missing from your
JsonSerializerContext, only in projects that need one (see below). - LAGOM010 for an endpoint class (one that implements
ILagomEndpoint) without a route attribute, which would otherwise silently never be mapped. LAGOM001 is the reverse: a route attribute on a class that does not implement exactly oneILagomEndpointinterface. Abstract and generic classes are endpoint bases, not endpoints, and are not asked for a route. - One NuGet package,
LagomEndpoints, with the generator and the analyzer inside it.
Not yet: positional record requests on GET, collections in the query string, form and file binding,
Configure, groups, behaviors, result helpers, OpenAPI metadata, benchmarks.
Request and response types next to the endpoint
The recommended layout is one file per endpoint, named after it, with the request and response types declared above
the endpoint class as <Endpoint>Request and <Endpoint>Response (GetOrder.cs holds GetOrderRequest,
GetOrderResponse and GetOrder). Nested Request and Response types inside the endpoint class work just as well;
the generator and the analyzers support both.
StyleCop would report the colocated layout as SA1402 (one type per file) and SA1649 (file name must match the first
type). The LagomEndpoints package includes a diagnostic suppressor that suppresses exactly those two rules for
top-level types named after an endpoint in the same file plus an allowed suffix (LAGOMS001 for SA1402, LAGOMS002 for
SA1649; the latter only when the file is named after an endpoint in it). Any other extra type in the file is still
reported. Request and Response are always allowed; add more suffixes in .editorconfig:
[*.cs]
lagom_endpoints.additional_colocated_type_suffixes = Item, Mapper, Validator
The suppressor works by rule id, wherever analyzers run (the IDE and the build). It still applies when
TreatWarningsAsErrors or an .editorconfig severity of error raises the two rules to errors; Roslyn only refuses to
suppress rules whose default severity is error, and SA1402 and SA1649 are warnings by default.
JSON and JsonSerializerContext
A normal ASP.NET Core app needs no JsonSerializerContext. Request bodies and JSON results go through the app's HTTP
JSON options, and by default those resolve any type through reflection. samples/TodoApi works this way.
You need a context only when reflection-based JSON is off: with Native AOT (PublishAot) or trimming
(PublishTrimmed), or in a library that says it is IsAotCompatible or IsTrimmable. List every type an endpoint
reads from or writes to JSON, and add the context in front of the default resolver, as samples/ShopApi does:
[JsonSerializable(typeof(CreateOrderRequest))]
[JsonSerializable(typeof(CreateOrderResponse))]
internal sealed partial class ShopApiJsonContext : JsonSerializerContext;
builder.Services.ConfigureHttpJsonOptions(options =>
options.SerializerOptions.TypeInfoResolverChain.Insert(0, ShopApiJsonContext.Default));
In those projects, and only there, the analyzer reports LAGOM009 (warning) for each type an endpoint needs that no
[JsonSerializable(typeof(...))] in the project lists:
'CreateOrderRequest' is read from JSON by 'CreateOrder', but no JsonSerializerContext in this project lists it; with Native AOT or trimming there is no reflection fallback, so add [JsonSerializable(typeof(CreateOrderRequest))] to a JsonSerializerContext and register it with ConfigureHttpJsonOptions
The types it checks are the request type when it is read from the body, and the T of Ok<T>, Created<T>,
CreatedAtRoute<T>, Accepted<T>, AcceptedAtRoute<T>, JsonHttpResult<T>, BadRequest<T>, NotFound<T>,
Conflict<T>, UnprocessableEntity<T> and InternalServerError<T>, also inside Results<...>. The package's
build/LagomEndpoints.props makes PublishAot, IsAotCompatible, PublishTrimmed and IsTrimmable visible to the
analyzer. If a type is still missing at runtime, the error says whether to list it in the context (AOT, trimming) or
to stop replacing the default resolver (everything else).
Layout
| Path | What |
|---|---|
src/LagomEndpoints |
Runtime: interfaces, route attributes, binding helpers |
src/LagomEndpoints.Generators |
The incremental source generator; reports no diagnostics |
src/LagomEndpoints.Analyzers |
The analyzer that reports LAGOM001 to LAGOM011, and the colocated type suppressor |
src/LagomEndpoints.Shared |
Endpoint parsing and models, compiled into both the generator and the analyzer (no project of its own) |
samples/ShopApi |
Sample API, Native AOT enabled, with a JsonSerializerContext |
samples/TodoApi |
Sample API without Native AOT and without a JsonSerializerContext |
tests/LagomEndpoints.Generators.Tests |
Generator output, registration and caching tests |
tests/LagomEndpoints.Analyzers.Tests |
Diagnostic and suppressor tests |
tests/ShopApi.Tests |
HTTP tests against the AOT sample |
tests/TodoApi.Tests |
HTTP tests against the sample without a context |
Commands
dotnet test
dotnet run --project samples/ShopApi
dotnet run --project samples/TodoApi
dotnet publish samples/ShopApi -c Release -r win-x64
Generated code for the sample lands in samples/ShopApi/obj/generated.
License
Apache-2.0
| Product | Versions 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. |
-
net10.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.