Kanject.Core.Api.Abstractions 3.13.0

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

Kanject.Core.Api.Abstractions

Kanject.Core.Api.Abstractions holds the contract types shared by Kanject ASP.NET Core services and their service layers: the JSON response envelope and pagination models, the ApiResponseCode vocabulary, ApiServiceException, minimal-API result helpers, FluentValidation rules with XSS screening, and the identity interfaces the controller helpers build on.

Reference it directly from class libraries (services, validators, endpoint modules) that must speak the same response and error language as the web host without depending on a specific edge package. Kanject.Core.Api and Kanject.Core.ApiV2 both reference it, so web projects using either get it transitively.

Installation

dotnet add package Kanject.Core.Api.Abstractions

Targets .NET 8, .NET 9 and .NET 10, and is marked Native AOT / trimming compatible. It depends on Kanject.Core and FluentValidation, and uses ASP.NET Core types (IResult, ModelStateDictionary), so it is intended for ASP.NET Core applications and the libraries they call.

Quick start

A minimal-API endpoint that returns the standard envelope and signals an expected failure:

using Kanject.Core.Api.Abstractions.Endpoints;
using Kanject.Core.Api.Abstractions.Enums;
using Kanject.Core.Api.Abstractions.Exceptions;
using Kanject.Core.Api.Abstractions.Models;

app.MapGet("/api/orders/{id:guid}", async (Guid id, IOrderStore store, CancellationToken ct) =>
{
    var order = await store.FindAsync(id, ct)
        ?? throw new ApiServiceException("id", "The order does not exist.", ApiResponseCode.NotFound);

    return order.ApiResponse("Order retrieved.");
});

app.MapGet("/api/orders", async (int pageSize, string? pageToken, IOrderStore store, CancellationToken ct) =>
{
    var page = await store.ListAsync(pageSize, pageToken, ct);
    var metadata = new PayloadMetadata(pageSize, page.Items.Count, pageToken: page.NextToken);

    return page.Items.ApiResponse(metadata);
});

This package defines ApiServiceException but does not translate it into an HTTP response. The exception middleware in Kanject.Core.Api (Kanject envelope) or Kanject.Core.ApiV2 (Problem Details) does that; without one of them, register your own handler.

The response envelope

ResponseBase<T> / Response<T> serialize as:

{
  "data": { "id": "3f2c…" },
  "message": "Order retrieved.",
  "responseCode": "0",
  "status": 200
}
Factory responseCode (unless you pass one) status
Response<T>.Success(data, message, responseCode) "0" (Success); message defaults to "Success" 200
Response<T>.Failed(errorMessage, responseCode) "1" (Error) 400
Response<T>.Warning(warningMessage, data, responseCode) "3" (Warning) 400

responseCode is a business code carried as a string — the numeric value of an ApiResponseCode by default, or any code you supply. status is a body field; the HTTP status of the response is set separately by whoever writes it (Results.Ok, a controller helper, the exception middleware).

Pagination

  • PayloadMetadata (readonly struct) — PageSize, PageItemCount, PageToken, HasNextPage, Custom. The constructor sets HasNextPage = true whenever pageToken is non-empty (and not "{}"), so passing the continuation token is enough. PayloadMetadata.CreateEmpty(pageSize, pageToken) builds an empty page.
  • ApiResponseDataset<T> — what paginated responses put in data: Dataset, PageSize, PageItemCount, PageToken, HasNextPage, Custom.
  • PaginatedQueryModel — base class for requests with pageSize / pageToken.

Response codes

ApiResponseCode (namespace Kanject.Core.Api.Abstractions.Enums) is the shared business-code vocabulary. The value in responseCode is the member's number:

Code Member Code Member
0 Success 8 BadRequest
1 Error 9 InternalServerError
2 ValidationError 10 ServiceUnavailable
3 Warning 11 TooManyRequests
4 Unauthorized 12 Created
5 NotFound 13 Accepted
6 Forbidden 14 NoContent
7 Conflict

In the legacy style the HTTP status an edge package assigns is its own mapping — the exception middleware in Kanject.Core.Api / Kanject.Core.ApiV2 maps ValidationError → 400, Unauthorized → 401, NotFound → 404, Success → 200, and everything else → 500. In the envelope style (below) every code answers the status it declares, through ApiResponseCodeExtensions: code.ToHttpStatusCode(), code.ToErrorCode() (its snake_case name, e.g. not_found), code.ToUserMessage() and ApiResponseCodeExtensions.FromHttpStatusCode(status). One exception is kept on purpose: ValidationError answers 400, as every Kanject edge has, not the 422 its declaration names.

Exceptions

Constructor Use
ApiServiceException(key, message, apiResponseCode = ApiResponseCode.ValidationError) Expected failure tied to a field or concept (key becomes the validation key)
ApiServiceException(message, responseCode, exception = null) Expected failure with an explicit code
ApiServiceException(message) / (message, innerException) Generic failure (Error)
ApiValidationException(message, key = "model") Shorthand for a ValidationError

ExceptionKey and ResponseCode are exposed as properties for custom middleware.

The envelope style (opt-in)

The second shape this package defines is the envelope: every JSON body is an object holding exactly one of data or error, and the HTTP status is carried once, never repeated in the body. It is the shape of the Kanject Developer APIs, and a host answers in it from controllers (Kanject.Core.Api / Kanject.Core.ApiV2) and from minimal APIs alike, so a service moves between the two styles without its clients noticing.

200  { "data": { "id": "lic_1", "sku": "dyno-business" } }
200  { "data": [ { "id": "lic_1" } ], "meta": { "nextPageToken": "eyJr…" } }
201  { "data": { … } }                       with a Location header
204  (no body)
400  { "error": { "code": "validation_error", "message": "Required", "fields": { "email": ["Required"] } } }
409  { "error": { "code": "conflict", "message": "Taken." } }
429  { "error": { "code": "too_many_requests", "message": "…", "retryAfter": 30 } }   with Retry-After

meta appears only when another page exists; fields and retryAfter only when they have a value; data is written even when it is null.

Opting a host in

using Kanject.Core.Api.Abstractions.Extensions;

builder.Services.AddCoreApiEnvelope();   // the controller helpers, the exception middleware, MVC's automatic 400 and its client-error mapping switch shape
var app = builder.Build();
app.UseCoreApiEnvelope();                // unknown route 404, wrong method 405, unsupported type 415, crashes 500: the envelope too

A host that does not call AddCoreApiEnvelope() answers in the legacy shapes above, byte for byte. ApiResponseOptions.Style (ApiResponseStyle.Legacy | Envelope) is the switch; the minimal-API helpers below always write the envelope. In an MVC host the controller helpers and the exception middleware write the envelope through MVC's formatters, so AddJsonOptions applies to data as it does to the legacy bodies; the minimal-API helpers read ConfigureHttpJsonOptions, as every TypedResults does. The envelope's own names and omissions are fixed by attributes, so neither set of options can move them.

Types

Type Role
ApiData<T>, ApiMeta The success body: data, and meta.nextPageToken on a paged list
ApiErrorBody, ApiErrorDetail The failure body: error.code, error.message, optional error.fields and error.retryAfter
ServiceFailure What an operation refuses with: StatusCode, snake_case Code, Message, optional Fields and RetryAfter; ServiceFailure.For(ApiResponseCode, message?), failure.ForField("memberIds")
ServiceResult<T> A value or a ServiceFailure, with implicit conversions from both, so a Business method returns one and no caller can forget the error check
ApiPage<T> A page's items and its next token; ApiPage<T>.From(items, PayloadMetadata) keeps the token only when HasNextPage
PageRequest, IPageTokenProtector, PageTokenOptions, PageFailures Sealed page tokens: the page a request asks for, the protector AddCorePageTokens registers, its keys and lifetime, and the two paging refusals (below)
[RawResponse("reason")] Marks a route that keeps its own shape because a protocol or a shipped client fixes it (/.well-known/*, a feed, a webhook acknowledgement)

Sealed page tokens

meta.nextPageToken is whatever you put in ApiPage<T>. A store's own continuation token, such as a DynamoDB last-evaluated key, is readable and editable by the client that receives it. On a list that only ever shows the caller's own rows that is harmless; on a list that crosses tenants or organisations an edited cursor pages someone else's rows. Seal it with one registration (namespace Kanject.Core.Api.Abstractions.Paging, Core proposal 0033 D6):

using Kanject.Core.Api.Abstractions.Endpoints;
using Kanject.Core.Api.Abstractions.Extensions;
using Kanject.Core.Api.Abstractions.Paging;

// Key: 256 bits of base64 from the host's secrets (PageTokenOptions.NewKey() makes one).
// PreviousKeys:0…n open tokens after a rotation; Lifetime defaults to 01:00:00.
builder.Services.AddCorePageTokens(builder.Configuration.GetSection("PageTokens"));

app.MapGet("/orgs/{orgId}/licenses", ListLicenses);

static async Task<Results<Ok<ApiData<IReadOnlyList<LicenseView>>>, JsonHttpResult<ApiErrorBody>>> ListLicenses(
    string orgId, HttpContext httpContext, ILicenseManager licenses)
{
    var read = PageRequest.Read(httpContext, defaultSize: 25, maxSize: 100);   // opens ?pageToken=, clamps ?pageSize=
    if (read.Failure is { } failure)
        return failure.ToApiError(httpContext);

    var request = read.Value!;
    ServiceResult<ApiPage<LicenseView>> page = await licenses.ListAsync(orgId, request.PageSize, request.Cursor);   // NextPageToken = the store's cursor
    return page.ToApiPage(httpContext, request);   // seals the next cursor to this list
}
  • The token. AES-256-GCM under Key; base64url over a version byte, a random nonce, the write time and the cursor, and the tag; at most 4096 characters. The associated data is the list's scope, PageRequest.ScopeOf(request): the method, the path, and the query without pageSize and pageToken (names in lower case, sorted). So a client can neither read nor edit the cursor, nor carry a token to another organisation's list or another filter, nor use it past Lifetime. Clocks may differ by five minutes between the instance that writes a token and the one that reads it.
  • The refusals. A token that does not open, whatever the reason (malformed, another key, another list, expired), is 400 invalid_page_token on pageToken, and the client starts the list again. A pageSize that is not a whole number is 400 bad_request on pageSize; one out of range is clamped.
  • Startup. AddCorePageTokens (from a section, or options => options.Key = …) checks the settings when the host starts: a missing key, a key that is not 256 bits of base64, or a lifetime that is not positive stops the host. The section is read by hand, so it binds the same under Native AOT, with no reflection and no binder generator. A sealing writer or PageRequest.Read in a host without the registration throws rather than passing the cursor through.
  • Other writers. service.ToApiPage(items, metadata, httpContext, request) seals the legacy PayloadMetadata token the same way. A controller, or a writer of your own, injects IPageTokenProtector and calls protector.Seal(page, PageRequest.ScopeOf(Request)) before ApiPageResponse(page), and protector.TryUnprotect(token, scope, out var cursor) to open one.
  • Rotation. Move the old key to PreviousKeys:0 and set a new Key; drop the old key once a Lifetime has passed.

One failure from every way a service refuses

ServiceFailureMappingExtensions.ToServiceFailure(…) turns a thrown ApiServiceException (its code's status and name; for ValidationError the exception key, or model, as the field with every message), any Exception (500 internal_server_error, the message shown only in a Development host), an IService that set HasError (its StatusCode or its code's status, its ResponseCode as a wire code, every Errors entry as a field), a ModelStateDictionary and data-annotation ValidationResults (400 validation_error with fields) into one ServiceFailure. The controller helpers and the exception middleware write the legacy shapes and the envelope from that same value.

Minimal-API helpers for the envelope

Namespace Kanject.Core.Api.Abstractions.Endpoints, class ApiEnvelopeResultExtensions; each returns typed results, so the shapes reach OpenAPI:

Extension Result
result.ToApiResponse(httpContext) on a ServiceResult<T> 200 {"data": …}, or the failure with its status
result.ToApiCreated(value => location, httpContext) 201 with Location, or the failure
result.ToApiAccepted(httpContext) 202, or the failure
result.ToApiNoContent(httpContext) 204, or the failure
result.ToApiPage(httpContext) on a ServiceResult<ApiPage<T>>; page.ToApiPage() 200 with data and, when a next token exists, meta
result.ToApiPage(httpContext, request) on a ServiceResult<ApiPage<T>> The same, with the next token, the store's cursor, sealed to the list request read
failure.ToApiError(httpContext) The failure's status with {"error": …}; a 429 also sends Retry-After
failure.ToApiErrorBody(), response.SetRetryAfter(failure), page.ToApiData() The bodies alone and the one header, for a writer of your own (the controllers use them)
service.ToApiResponse(payload, httpContext) on an IService The service's failure when HasError, else 200 {"data": payload} — the envelope form of service.HasError ? ApiErrorResponse(service.Errors) : ApiResponse(payload)
service.ToApiPage(items, metadata, httpContext) The service's failure when HasError, else the page from the legacy PayloadMetadata
service.ToApiPage(items, metadata, httpContext, request) The same, with the store's token sealed to the list request read

Under Native AOT the success bodies use the host's JSON options, so list each closed ApiData<T> you write in your JsonSerializerContext; the error body falls back to this package's own source-generated metadata, so a refusal never needs reflection. The SDK's Native AOT smoke publishes and runs these helpers with every trim and AOT warning treated as an error. (Controllers are MVC, which ASP.NET Core does not support under Native AOT in any style.)

Minimal-API helpers (legacy style)

Namespace Kanject.Core.Api.Abstractions.Endpoints, class EndpointExtensions — extension methods returning IResult in the legacy Response<T> shape:

Extension Result
payload.ApiResponse(message, responseCode) 200 with the success envelope
items.ApiResponse(metadata, message, responseCode) 200 with an ApiResponseDataset<T> envelope
validationResults.ApiErrorResponse() 400 envelope from IEnumerable<ValidationResult>; message is the first error
modelState.ApiErrorResponse() 400 envelope from a ModelStateDictionary; message is the first error
modelState.ValidationErrorList() The same envelope as a Response<IEnumerable<string>> value (not an IResult)
modelState.ValidationErrorString() / GetFirstValidationError() All messages joined with "; ", or the first message

Namespace Kanject.Core.Api.Abstractions.Extensions adds current-user helpers on ClaimsPrincipal and HttpContext: GetCurrentUserId(), GetCurrentUserOrganizationId(), GetCurrentUserGroups() and GetCurrentUserAsync(). They resolve your IUserIdentityClaimsPrincipal through the application builder registered with app.UseAppUtilityService(...) (from Kanject.Core), in a new scope created from the root provider.

Validation

FluentValidation rule extensions in Kanject.Core.Api.Abstractions.Extensions:

using FluentValidation;
using Kanject.Core.Api.Abstractions.Enums;
using Kanject.Core.Api.Abstractions.Extensions;

public sealed record CreateOrderRequest(string CustomerName, string Email, string Notes, string CallbackUrl);

public sealed class CreateOrderRequestValidator : AbstractValidator<CreateOrderRequest>
{
    public CreateOrderRequestValidator()
    {
        RuleFor(x => x.CustomerName).NotEmpty().MustMatchKnownNames();
        RuleFor(x => x.Email).MustBeValidEmailAddress();
        RuleFor(x => x.Notes).MustBeSafeFromXss(XssValidationMode.Standard, maxLength: 2000);
        RuleFor(x => x.CallbackUrl).MustBeValidUrl(allowedSchemes: ["https"]);
    }
}
Rule Checks
MustBeSafeFromXss(mode, customAllowedChars, allowEmpty, maxLength, enableAdvancedDetection) Character allow-list for the XssValidationMode, known script/event-handler/encoding patterns, and optional template/CSS/SQL-injection heuristics. Error code XSS_VALIDATION_FAILED.
MustBeSafeHtml(allowedTags, allowedAttributes, allowEmpty) HTML restricted to an allow-list of tags and attributes. Error code UNSAFE_HTML_CONTENT.
MustNotIncludeHarmfulXssProneCharacters(additionalAllowedChars, allowEmpty) Letters, digits, space and .,!?-_@, plus a limited set of extra punctuation you opt into
MustBeValidUrl(allowedSchemes, allowEmpty) Absolute URL with an allowed scheme (http/https by default) and no script payloads. Error code INVALID_OR_UNSAFE_URL.
MustMatchKnownNames() Letters, digits, hyphens and spaces
MustContainOnlyAlphanumericAndSpaces() Letters, digits and spaces
MustBeValidEmailAddress() Basic local@domain.tld format

XssValidationMode: Strict, Standard (the default), Html, Markdown, Custom. The built-in character sets are ASCII-only and exclude line breaks, so accented letters, non-Latin scripts and multi-line text fail every mode except Custom with your own character set.

To surface FluentValidation results through MVC model state, use ModelState.TryAddValidationErrors(validationResult) — property names are camel-cased as keys. Overloads also merge another ModelStateDictionary or a ValidationProblemDetails. GetValidationErrors() joins all messages with ", ".

Service-layer and identity contracts

  • IService / AbstractService — a disposable service base that accumulates errors in a ModelStateDictionary (Errors, HasError) alongside ResponseCode, StatusCode and ResponseMessage, for services that report failures instead of throwing.
  • IUserIdentityClaimsPrincipal — implement it for your identity provider: GetUserId, GetUserGroups, GetUserPermissions, GetUserIdentityInformation. The current-user helpers here and in Kanject.Core.Api / Kanject.Core.ApiV2 call it.
  • IApplicationUser, IApplicationUserGroup — user and group shapes returned by that reader.
  • HttpRequestLoggerExtensions.LogHttpRequestAsync(request, exception) — prints the URL, verb, headers (except Authorization), full request body, and exception details to the console. The edge packages call it for unhandled exceptions; mind personal data in bodies and cookies.

Attributes for generated minimal APIs

[ApiEndpoints] and the [HttpGet], [HttpPost], [HttpPut], [HttpDelete], [HttpPatch] attributes in Kanject.Core.Api.Abstractions.Attributes describe minimal-API endpoint groups as static classes. They do nothing on their own — add the Kanject.Core.Api.Annotations source generator to turn them into route registrations. These verb attributes are distinct from the MVC attributes of the same names in Microsoft.AspNetCore.Mvc.

Package Role Availability
Kanject.Core.Api Controllers, exception middleware (Kanject envelope errors) and tenant middleware nuget.org
Kanject.Core.ApiV2 Controllers, exception middleware (Problem Details errors) and tenant middleware nuget.org
Kanject.Core.Api.Annotations Source generator and analyzers for [ApiEndpoints] classes nuget.org
Kanject.Core.Api.Aws.Extensions Parameter Store configuration and CloudWatch-friendly console output nuget.org
Kanject.Core Core utilities this package builds on, including UseAppUtilityService nuget.org

License

Licensed under the Kanject Code Libraries License Agreement (KCLLA); the full text ships in this package as LICENSE.md. Organizations whose trailing-twelve-month gross revenue and total funding raised are each below US$250,000 may use it at no cost under the Free Tier. At or above either threshold a commercial license is required — contact commercial@kanjectbusiness.com.

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 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 (5)

Showing the top 5 NuGet packages that depend on Kanject.Core.Api.Abstractions:

Package Downloads
Kanject.Core.Api.Aws.Extensions

Kanject core AWS api Extensions

Kanject.Core.Adapter

Kanject service adapter library

Kanject.Core.Api

Kanject core api

Kanject.Core.ApiV2

Kanject core api V2

Kanject.Core.Logs.Abstractions

Kanject Logs Abstractions

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
4.0.1 0 11/21/2026
4.0.0 220 11/11/2026
3.14.0 260 11/5/2026
3.13.0 184 11/4/2026
3.12.0 225 11/2/2026
3.11.0 597 10/5/2026
3.10.0 243 10/2/2026
3.9.1 260 9/27/2026
3.9.0 191 9/27/2026
3.8.7 183 9/26/2026
3.8.6 223 9/7/2026
3.8.5 201 8/27/2026
3.8.4 217 8/22/2026
3.8.3 225 8/10/2026
3.8.2 210 8/9/2026
3.8.1 221 8/5/2026
3.8.0 218 8/5/2026
3.7.0 222 8/3/2026
3.6.7 239 7/30/2026
3.6.6 251 7/18/2026
Loading failed

- AddCorePageTokens seals next-page tokens with one registration. PageRequest.Read opens a token only on the list that wrote it and the sealing ToApiPage overloads seal the store cursor with AES-GCM.