Kanject.Core.Api
3.9.0
Prefix Reserved
See the version list below for details.
dotnet add package Kanject.Core.Api --version 3.9.0
NuGet\Install-Package Kanject.Core.Api -Version 3.9.0
<PackageReference Include="Kanject.Core.Api" Version="3.9.0" />
<PackageVersion Include="Kanject.Core.Api" Version="3.9.0" />
<PackageReference Include="Kanject.Core.Api" />
paket add Kanject.Core.Api --version 3.9.0
#r "nuget: Kanject.Core.Api, 3.9.0"
#:package Kanject.Core.Api@3.9.0
#addin nuget:?package=Kanject.Core.Api&version=3.9.0
#tool nuget:?package=Kanject.Core.Api&version=3.9.0
Kanject.Core.Api
Kanject.Core.Api supplies the HTTP-edge conventions shared by Kanject ASP.NET Core services: standardized response envelopes, controller helpers, exception-to-HTTP mapping, and request-scoped tenant resolution.
Use it to keep transport concerns at the edge. Controllers return one predictable response shape, domain/application services throw ApiServiceException for expected failures, and downstream services consume ITenantContext without depending on HttpContext.
Installation
dotnet add package Kanject.Core.Api
The package supports .NET 8, .NET 9, and .NET 10. It brings in Kanject.Core.Api.Abstractions (response models, ApiResponseCode, ApiServiceException), Kanject.Core.Tenancy (ITenantContext) and Microsoft.AspNetCore.Authentication.JwtBearer.
Kanject.Core.Api or Kanject.Core.ApiV2?
The two packages ship side by side and share the success envelope, the pagination helpers, the tenant middleware and the registration method names. They differ in how failures reach the client and in the controller's default authorization:
Kanject.Core.Api (this package) |
Kanject.Core.ApiV2 |
|
|---|---|---|
| Error body from the exception middleware | Kanject envelope (message, responseCode) |
RFC 7807 ProblemDetails / ValidationProblemDetails |
BaseController authorization |
[Authorize] with the JWT bearer scheme |
None — add your own [Authorize] |
| Namespaces | Kanject.Core.Api.* |
Kanject.Core.ApiV2.* |
The envelope style (AddCoreApiEnvelope(), see below) |
Available | Available |
Choose this package when your clients already parse the Kanject envelope for errors too; choose Kanject.Core.ApiV2 when they expect standard Problem Details. Use one per service — the extension methods have identical names, so importing both namespaces makes the calls ambiguous. A host on either package can opt into the envelope style instead, in which both answer identically (see The envelope style).
Quick start
using Kanject.Core.Api.Extensions;
using Microsoft.AspNetCore.Authentication.JwtBearer;
var builder = WebApplication.CreateBuilder(args);
// BaseController requires the JWT bearer scheme.
builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = builder.Configuration["Jwt:Authority"];
options.Audience = builder.Configuration["Jwt:Audience"];
});
builder.Services.AddAuthorization();
builder.Services.AddControllers();
builder.Services.AddCoreExceptionHandlerMiddleware();
builder.Services.AddTenantMiddleware();
builder.Services.AddScoped<OrderService>();
var app = builder.Build();
app.UseRouting();
app.UseAuthentication();
app.UseCoreExceptionHandlerMiddleware();
app.UseTenantMiddleware();
app.UseAuthorization();
app.MapControllers();
app.Run();
Pipeline order matters: authenticate first if tenant/user resolution depends on identity; run the exception middleware before components whose exceptions it should translate; populate the tenant context before invoking tenant-aware services.
Real-world controller
using Kanject.Core.Api.Abstractions.Models;
using Kanject.Core.Api.Controller;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/orders")]
public sealed class OrdersController(OrderService orders) : BaseController
{
/// <summary>Returns one page of orders for the tenant in the x-tenant-id header.</summary>
[HttpGet]
[ProducesResponseType(typeof(Kanject.Core.Api.Models.Response<ApiResponseDataset<OrderDto>>), 200)]
public async Task<IActionResult> ListAsync(
[FromQuery] int pageSize = 25,
[FromQuery] string? pageToken = null,
CancellationToken cancellationToken = default)
{
var page = await orders.ListAsync(pageSize, pageToken, cancellationToken);
var metadata = new PayloadMetadata(
pageSize: pageSize,
pageItemCount: page.Items.Count,
hasNextPage: page.NextToken is not null,
pageToken: page.NextToken,
custom: new Dictionary<string, object>
{
["resultSource"] = "orders"
});
return ApiResponse(page.Items, metadata, "Orders retrieved.");
}
}
BaseController is protected with the JWT bearer scheme by default. Use the normal ASP.NET Core [AllowAnonymous] attribute only for endpoints that are intentionally public.
Current-user helpers
BaseController also exposes CurrentUserId, CurrentUserOrganizationId, CurrentUserGroups and CurrentUser. They delegate to an IUserIdentityClaimsPrincipal (from Kanject.Core.Api.Abstractions) that you implement for your identity provider, and they locate it through the application builder registered with UseAppUtilityService (from Kanject.Core):
using Kanject.Core.Api.Abstractions.Interfaces;
using Kanject.Core.UtilityServices.Extensions;
builder.Services.AddSingleton<IUserIdentityClaimsPrincipal, MyClaimsReader>();
// ...
app.UseAppUtilityService(builder.Environment);
CurrentUserOrganizationIdis taken from the first group containingOrg#(the text after the last#);CurrentUserGroupsreturns the remaining groups, each trimmed the same way.- Each property access resolves the reader from a new scope created from the root service provider, not from the request scope — register the reader as a singleton or transient, or inject it into the controller directly.
CurrentUserblocks onGetUserIdentityInformation; in async actions, prefer awaiting the reader yourself.
Tenant-aware application service
AddTenantMiddleware() registers a scoped ITenantContext. UseTenantMiddleware() populates it from the canonical x-tenant-id request header.
using Kanject.Core.Api.Abstractions.Enums;
using Kanject.Core.Api.Abstractions.Exceptions;
using Kanject.Core.Tenancy;
public sealed class OrderService(ITenantContext tenant, IOrderRepository repository)
{
public Task<Order?> GetAsync(Guid id, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(tenant.TenantId))
{
throw new ApiServiceException(
"tenant",
"The x-tenant-id header is required.",
ApiResponseCode.ValidationError);
}
return repository.GetAsync(tenant.TenantId, id, cancellationToken);
}
}
The middleware intentionally leaves TenantId empty when the header is absent. This lets public or tenant-neutral endpoints coexist with tenant-aware ones; services that require a tenant must guard the boundary explicitly.
Response contract
Successful responses use the following JSON envelope:
{
"data": {},
"message": "Success",
"responseCode": "0",
"status": 200
}
Validation-capable responses may also include:
{
"data": null,
"message": "Postal code is required.",
"responseCode": "2",
"status": 0,
"validationMessages": ["Postal code is required."]
}
Controller helpers
| Helper | Result |
|---|---|
ApiResponse(payload, message, responseCode) |
HTTP 200 with Response<T> success envelope |
ApiResponse(items, metadata, message, responseCode) |
HTTP 200 with ApiResponseDataset<T> pagination envelope |
ApiErrorResponse(validationResults) |
HTTP 400 with validation details |
ApiErrorResponse(ModelState) |
HTTP 400 with model-state validation details |
ApiErrorResponse(message, code, statusCode) |
Chosen HTTP status with failure envelope |
ApiResponse(ServiceResult<T>) |
HTTP 200 with the value, or the failure with its status |
ApiCreatedResponse(result, location), ApiAcceptedResponse(result), ApiNoContentResponse(result) |
201 with Location, 202, or 204 — or the failure |
ApiPageResponse(ApiPage<T>), ApiPageResponse(ServiceResult<ApiPage<T>>) |
HTTP 200 with the page, in the host's style |
ApiErrorResponse(ServiceFailure) |
The failure's status; validationMessages when it names fields, else the failure envelope |
ResponseStyle |
Legacy, or Envelope once the host called AddCoreApiEnvelope() |
GetModelStateValidationErrors() |
Semicolon-separated validation messages |
GetModelStateValidationErrorsAsList() |
Response containing all validation messages |
PayloadMetadata carries PageSize, PageItemCount, PageToken, HasNextPage, and an optional Custom dictionary. A non-empty page token automatically marks HasNextPage as true.
Exception middleware
Register and activate the default middleware:
services.AddCoreExceptionHandlerMiddleware();
app.UseCoreExceptionHandlerMiddleware();
Expected application failures should use ApiServiceException:
throw new ApiServiceException(
"orderId",
"The order does not exist.",
ApiResponseCode.NotFound);
The default mapper currently handles these response codes:
ApiResponseCode |
HTTP status |
|---|---|
Success |
200 |
ValidationError |
400 |
Unauthorized |
401 |
NotFound |
404 |
Error and all other values |
500 |
Unhandled exceptions are logged through the SDK request logger and returned as a generic error envelope. Do not rely on exception messages being returned to clients; production responses intentionally avoid leaking internal details. The request log (LogHttpRequestAsync from Kanject.Core.Api.Abstractions) prints the URL, verb, every header except Authorization, and the full request body — keep that in mind for endpoints that accept personal data or credentials in cookies or custom headers.
Custom middleware
Register a custom IMiddleware when an application needs a wider status mapping, trace IDs, or another error format:
services.AddCoreExceptionHandlerMiddleware<CommerceExceptionMiddleware>();
app.UseMiddleware<CommerceExceptionMiddleware>();
The generic registration method registers the type; activate that same middleware type explicitly in the pipeline.
The envelope style (opt-in)
The shapes above are the legacy style. Call AddCoreApiEnvelope() (from Kanject.Core.Api.Abstractions.Extensions) and the same controller code, the exception middleware and MVC's automatic 400 answer in the envelope: every JSON body is an object holding exactly one of data or error, and the HTTP status is carried once. It is the shape of the Kanject Developer APIs and of the minimal-API helpers in Kanject.Core.Api.Abstractions, so a service moves between controllers and minimal APIs without its clients noticing.
builder.Services.AddControllers();
builder.Services.AddCoreExceptionHandlerMiddleware();
builder.Services.AddCoreApiEnvelope();
var app = builder.Build();
app.UseCoreApiEnvelope(); // unknown route 404, wrong method 405, crashes 500: the envelope too; AddCoreApiEnvelope() gives [ApiController]'s own NotFound()/415 mapping the same shape
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseCoreExceptionHandlerMiddleware();
app.MapControllers();
200 { "data": { "id": "3f2c…" } } ApiResponse(order)
200 { "data": [ { "id": "3f2c…" } ], "meta": { "nextPageToken": "…" } } ApiResponse(items, metadata) with a next page
400 { "error": { "code": "validation_error", "message": "Required", "fields": { "email": ["Required"] } } } ApiErrorResponse(ModelState)
409 { "error": { "code": "conflict", "message": "Taken." } } a thrown ApiServiceException(…, ApiResponseCode.Conflict)
500 { "error": { "code": "internal_server_error", "message": "An unexpected error occurred on the server" } } any other exception
message and responseCode arguments carry nothing in this style; a numeric errorCode becomes its snake_case name ("7" → conflict), any other string is written as given, and a null one takes the code of the status. Every envelope body goes through MVC's formatters, so the converters and naming you set with AddJsonOptions apply to data exactly as they do to the legacy bodies. The exception middleware answers the status each ApiResponseCode declares, so a Conflict is 409 and a Forbidden 403, where the legacy mapper sends 500.
A Business layer that returns ServiceResult<T> (a value or a ServiceFailure) serves both styles through ApiResponse(result), ApiCreatedResponse, ApiAcceptedResponse, ApiNoContentResponse, ApiPageResponse and ApiErrorResponse(ServiceFailure): in a legacy host they write Response<T>, in an envelope host the envelope. Update [ProducesResponseType] declarations to ApiData<T> and ApiErrorBody when you opt in. Routes a protocol fixes keep their shape and carry [RawResponse("reason")].
Public surface at a glance
| Type or extension | Responsibility |
|---|---|
BaseController |
Authenticated controller base and response/model-state helpers; its ServiceResult<T> helpers and ResponseStyle follow the host's style |
Response<T> |
API envelope with validation messages |
AddCoreExceptionHandlerMiddleware |
Registers default or custom exception middleware |
UseCoreExceptionHandlerMiddleware |
Activates the default exception translator (the envelope once the host opted in) |
AddCoreApiEnvelope() / UseCoreApiEnvelope() (Kanject.Core.Api.Abstractions.Extensions) |
Opts the host into the envelope style and gives the answers no handler writes the same shape |
AddTenantMiddleware |
Registers scoped tenant context and resolver middleware |
UseTenantMiddleware |
Resolves x-tenant-id for each request |
ITenantContext |
Downstream, HTTP-independent tenant contract |
OpenAPI and documentation guidance
The README defines package behavior, but endpoint documentation should remain close to controller code so ASP.NET Core/OpenAPI tooling can extract it. For informative generated docs:
- Enable XML documentation in the web project.
- Add XML
<summary>,<remarks>,<param>,<returns>, and<response code="...">comments to controllers and actions. - Add
[ProducesResponseType]for every success and failure shape. - Use concrete DTOs instead of anonymous response objects.
- Document the required
x-tenant-idheader globally or through an OpenAPI operation filter. - Keep business response codes distinct from HTTP status codes in examples and client guidance.
Recommended project settings:
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
With Swashbuckle or NSwag, include the generated XML file and map action response types. A typical operation should describe both layers of status: for example, HTTP 404 plus responseCode: "5" for a missing order.
Testing guidance
- Integration-test middleware order and the complete JSON envelope, not only controller return types.
- Verify that two concurrent request scopes cannot observe one another's tenant IDs.
- Cover missing and whitespace-only tenant headers.
- Test every
ApiServiceExceptioncode actually used by the application; codes outside the default mapper resolve to HTTP 500. - Verify production responses do not expose stack traces or secret-bearing exception messages.
- Use
WebApplicationFactory<TEntryPoint>for the full request pipeline and a fixedITenantContextstub for isolated service tests.
Related packages
| Package | Role | Availability |
|---|---|---|
Kanject.Core.Api.Abstractions |
Response models, ApiResponseCode, ApiServiceException, validation and minimal-API helpers (dependency of this package) |
nuget.org |
Kanject.Core.ApiV2 |
The same edge conventions with RFC 7807 Problem Details error bodies | nuget.org |
Kanject.Core.Tenancy |
The ITenantContext contract (dependency of this package) |
nuget.org |
Kanject.Core.Api.Annotations |
Source generator for [ApiEndpoints] minimal-API endpoint groups |
nuget.org |
Kanject.Core.Api.Aws.Extensions |
Parameter Store configuration and CloudWatch-friendly console output | 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 | Versions 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. |
-
net10.0
- Kanject.Core.Api.Abstractions (>= 3.13.0)
- Kanject.Core.Tenancy (>= 3.12.1)
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 10.0.13)
-
net8.0
- Kanject.Core.Api.Abstractions (>= 3.13.0)
- Kanject.Core.Tenancy (>= 3.12.1)
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 8.0.32)
-
net9.0
- Kanject.Core.Api.Abstractions (>= 3.13.0)
- Kanject.Core.Tenancy (>= 3.12.1)
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 9.0.21)
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 |
|---|---|---|
| 4.0.1 | 0 | 11/21/2026 |
| 4.0.0 | 125 | 11/11/2026 |
| 3.10.1 | 97 | 11/10/2026 |
| 3.10.0 | 122 | 11/5/2026 |
| 3.9.0 | 94 | 11/4/2026 |
| 3.8.0 | 119 | 11/2/2026 |
| 3.7.1 | 166 | 10/22/2026 |
| 3.7.0 | 200 | 10/5/2026 |
| 3.6.1 | 108 | 10/5/2026 |
| 3.6.0 | 114 | 10/2/2026 |
| 3.5.1 | 142 | 9/27/2026 |
| 3.5.0 | 108 | 9/27/2026 |
| 3.4.7 | 110 | 9/26/2026 |
| 3.4.6 | 150 | 9/7/2026 |
| 3.4.5 | 126 | 8/27/2026 |
| 3.4.4 | 130 | 8/22/2026 |
| 3.4.3 | 137 | 8/10/2026 |
| 3.4.2 | 134 | 8/9/2026 |
| 3.4.1 | 136 | 8/5/2026 |
| 3.4.0 | 136 | 8/5/2026 |
- Takes Kanject.Core.Api.Abstractions 3.13.0.