Kanject.Core.ApiV2
4.3.0
Prefix Reserved
dotnet add package Kanject.Core.ApiV2 --version 4.3.0
NuGet\Install-Package Kanject.Core.ApiV2 -Version 4.3.0
<PackageReference Include="Kanject.Core.ApiV2" Version="4.3.0" />
<PackageVersion Include="Kanject.Core.ApiV2" Version="4.3.0" />
<PackageReference Include="Kanject.Core.ApiV2" />
paket add Kanject.Core.ApiV2 --version 4.3.0
#r "nuget: Kanject.Core.ApiV2, 4.3.0"
#:package Kanject.Core.ApiV2@4.3.0
#addin nuget:?package=Kanject.Core.ApiV2&version=4.3.0
#tool nuget:?package=Kanject.Core.ApiV2&version=4.3.0
Kanject.Core.ApiV2
Kanject.Core.ApiV2 supplies HTTP-edge conventions for ASP.NET Core services: a standard success envelope with pagination helpers, an exception middleware that writes RFC 7807 Problem Details, and request-scoped tenant resolution from the x-tenant-id header.
It is the Problem Details sibling of Kanject.Core.Api. Successful responses look the same in both packages; failures raised through the exception middleware come back as ProblemDetails / ValidationProblemDetails — the shape ASP.NET Core itself produces for automatic model validation and Results.Problem(...).
Installation
dotnet add package Kanject.Core.ApiV2
Targets .NET 9, .NET 10 and .NET 11. It brings in Kanject.Core.Api.Abstractions (response models, ApiResponseCode, ApiServiceException) and Kanject.Core.Tenancy (ITenantContext).
Kanject.Core.Api or Kanject.Core.ApiV2?
Both packages ship side by side. They share the success envelope, the pagination helpers, the tenant middleware and the registration method names (AddCoreExceptionHandlerMiddleware, UseTenantMiddleware, …). The differences:
Kanject.Core.Api |
Kanject.Core.ApiV2 (this package) |
|
|---|---|---|
| Error body from the exception middleware | Kanject envelope (message, responseCode) |
ProblemDetails / ValidationProblemDetails (title, status, detail, errors) |
BaseController.ApiErrorResponse(ModelState) |
HTTP 400 envelope with validationMessages |
HTTP 400 ValidationProblemDetails via ControllerBase.ValidationProblem |
BaseController authorization |
[Authorize] with the JWT bearer scheme |
None — apply [Authorize] yourself |
ApiErrorResponse(IEnumerable<ValidationResult>), GetModelStateValidationErrorsAsList() |
Available | Not available |
| Namespaces | Kanject.Core.Api.* |
Kanject.Core.ApiV2.* |
The envelope style (AddCoreApiEnvelope(), see below) |
Available | Available |
Use Kanject.Core.ApiV2 for new services whose clients expect standard Problem Details errors, or when you want to choose the authentication scheme per controller. Use Kanject.Core.Api when existing clients already parse the Kanject envelope for errors (responseCode, validationMessages). Pick 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.ApiV2.Extensions;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(/* your scheme */);
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: run the exception middleware before the components whose exceptions it should translate, and populate the tenant context before tenant-aware services run.
Controller
using Kanject.Core.Api.Abstractions.Models;
using Kanject.Core.ApiV2.Controller;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Authorize]
[Route("api/orders")]
public sealed class OrdersController(OrderService orders) : BaseController
{
[HttpGet]
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, page.Items.Count, pageToken: page.NextToken);
return ApiResponse(page.Items, metadata, "Orders retrieved.");
}
[HttpPost]
public async Task<IActionResult> CreateAsync(CreateOrderRequest request, CancellationToken cancellationToken)
{
if (!ModelState.IsValid)
return ApiErrorResponse(ModelState); // 400 ValidationProblemDetails
return ApiResponse(await orders.CreateAsync(request, cancellationToken), "Order created.");
}
}
Unlike Kanject.Core.Api, this BaseController carries no authorization attribute — the [Authorize] above is yours.
Controller helpers
| Helper | Result |
|---|---|
ApiResponse(payload, message, responseCode) |
HTTP 200 with the success envelope |
ApiResponse(items, metadata, message, responseCode) |
HTTP 200 with an ApiResponseDataset<T> pagination envelope |
ApiErrorResponse(ModelState) |
HTTP 400 ValidationProblemDetails; detail is the first validation message |
ApiErrorResponse(message, code, statusCode) |
Chosen HTTP status with the envelope's failure shape (not Problem Details) |
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; ValidationProblemDetails when it names fields, else the failure envelope |
ResponseStyle |
Legacy, or Envelope once the host called AddCoreApiEnvelope() |
GetModelStateValidationErrors() |
All model-state messages joined with "; " |
GetModelStateValidationError() |
The first model-state message |
CurrentUserId, CurrentUserOrganizationId, CurrentUserGroups, CurrentUser |
Current-user data from your IUserIdentityClaimsPrincipal |
The current-user properties need an IUserIdentityClaimsPrincipal registration and app.UseAppUtilityService(...) (from Kanject.Core.UtilityServices.Extensions). They resolve the reader from a new scope created from the root provider rather than the request scope, and end that scope before they return, so register it as a singleton or transient. CurrentUserOrganizationId comes from the first group containing Org#.
Success envelope
{
"data": { "id": "3f2c…", "status": "Placed" },
"message": "Order created.",
"responseCode": "0",
"status": 200
}
message defaults to "Success" and responseCode to "0" (ApiResponseCode.Success) when you don't pass them. Paginated responses put an ApiResponseDataset<T> in data (dataset, pageSize, pageItemCount, pageToken, hasNextPage, custom).
Error responses
Throw ApiServiceException (from Kanject.Core.Api.Abstractions.Exceptions) for expected failures:
throw new ApiServiceException("orderId", "The order does not exist.", ApiResponseCode.NotFound);
The middleware maps ApiServiceException.ResponseCode to the HTTP status and writes it into status; the exception message becomes detail:
ApiResponseCode |
HTTP status | Body |
|---|---|---|
ValidationError |
400 | ValidationProblemDetails with errors: { "<key>": ["<message>"] } (key defaults to model) |
Unauthorized |
401 | ProblemDetails |
NotFound |
404 | ProblemDetails |
Success |
200 | ProblemDetails |
Error and all other values |
500 | ProblemDetails |
{
"title": "One or more validation errors occurred.",
"status": 400,
"detail": "The x-tenant-id header is required.",
"errors": { "tenant": ["The x-tenant-id header is required."] }
}
title is a generic, code-dependent label; have clients branch on status (and errors for validation).
Any other exception becomes HTTP 500 with a generic detail. In the Development environment detail carries the underlying exception message instead. Unhandled exceptions are also logged with LogHttpRequestAsync, which prints the URL, verb, every header except Authorization, and the full request body.
To use a different mapping, register your own IMiddleware with services.AddCoreExceptionHandlerMiddleware<TMiddleware>() and activate it with app.UseMiddleware<TMiddleware>().
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.UseCoreExceptionHandlerMiddleware();
app.MapControllers();
The controller from the quick start now answers:
200 { "data": [ { "id": "3f2c…" } ], "meta": { "nextPageToken": "…" } } ApiResponse(items, metadata) with a next page
200 { "data": { "id": "3f2c…", "status": "Placed" } } ApiResponse(order)
400 { "error": { "code": "validation_error", "message": "Required", "fields": { "email": ["Required"] } } } ApiErrorResponse(ModelState)
410 { "error": { "code": "bad_request", "message": "Gone." } } ApiErrorResponse("Gone.", null, 410)
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 writes every thrown exception in the same shape, with the status its ApiResponseCode declares — so a Conflict is 409 and a Forbidden 403, where the legacy resolver sends 500:
| Thrown | Envelope answer |
|---|---|
ApiValidationException("Item not found", "itemId") |
400 {"error": {"code": "validation_error", "message": "Item not found", "fields": {"itemId": ["Item not found"]}}} |
ApiServiceException("x", "Taken.", ApiResponseCode.Conflict) |
409 {"error": {"code": "conflict", "message": "Taken."}} |
| Any other exception | 500 {"error": {"code": "internal_server_error", "message": "An unexpected error occurred on the server"}}; the exception's message only in a Development host |
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")].
Tenant resolution
AddTenantMiddleware() registers a scoped ITenantContext (from Kanject.Core.Tenancy); UseTenantMiddleware() fills TenantId from the x-tenant-id request header. When the header is missing or blank, TenantId stays empty — services that require a tenant must check it:
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);
}
}
Migrating from Kanject.Core.Api
- Swap the package and change
using Kanject.Core.Api.Controller;/.Extensions;toKanject.Core.ApiV2.Controller;/.Extensions;. - Add
[Authorize](with your scheme) wherever you relied onBaseController's built-in JWT bearer requirement. - Replace calls to
ApiErrorResponse(IEnumerable<ValidationResult>)andGetModelStateValidationErrorsAsList(). - Update clients and OpenAPI annotations: error bodies are now Problem Details, and model-state errors are keyed under
errorsrather than listed invalidationMessages.
Public surface at a glance
| Type or extension | Namespace | Responsibility |
|---|---|---|
BaseController |
Kanject.Core.ApiV2.Controller |
Controller base with envelope, Problem Details and current-user helpers; its ServiceResult<T> helpers and ResponseStyle follow the host's style |
CoreExceptionMiddleware |
Kanject.Core.ApiV2.Middlewares |
Translates exceptions into Problem Details, or into 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 |
TenantMiddleware |
Kanject.Core.ApiV2.Middlewares |
Reads x-tenant-id into the scoped tenant context |
AddCoreExceptionHandlerMiddleware() / <TMiddleware>() |
Kanject.Core.ApiV2.Extensions |
Registers the default or a custom exception middleware (singleton) |
UseCoreExceptionHandlerMiddleware() |
Kanject.Core.ApiV2.Extensions |
Adds the default exception middleware to the pipeline |
AddTenantMiddleware() / UseTenantMiddleware() |
Kanject.Core.ApiV2.Extensions |
Registers and activates tenant resolution |
Related packages
| Package | Role | Availability |
|---|---|---|
Kanject.Core.Api |
The same edge conventions with Kanject-envelope error bodies and a JWT-protected BaseController |
nuget.org |
Kanject.Core.Api.Abstractions |
Response models, the envelope types (ApiData<T>, ApiErrorBody, ServiceResult<T>, ServiceFailure), ApiResponseCode, ApiServiceException, validation and minimal-API helpers (dependency of this package) |
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 | 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. net11.0 is compatible. |
-
net10.0
- Kanject.Core.Api.Abstractions (>= 4.3.0)
- Kanject.Core.Tenancy (>= 4.0.0)
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 10.0.15)
-
net11.0
- Kanject.Core.Api.Abstractions (>= 4.3.0)
- Kanject.Core.Tenancy (>= 4.0.0)
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 11.0.0)
-
net9.0
- Kanject.Core.Api.Abstractions (>= 4.3.0)
- Kanject.Core.Tenancy (>= 4.0.0)
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 9.0.23)
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.3.0 | 67 | 11/24/2026 |
| 4.2.0 | 58 | 11/24/2026 |
| 4.1.0 | 74 | 11/22/2026 |
| 4.0.1 | 75 | 11/21/2026 |
| 4.0.0 | 150 | 11/11/2026 |
| 3.10.1 | 104 | 11/10/2026 |
| 3.10.0 | 122 | 11/5/2026 |
| 3.9.0 | 105 | 11/4/2026 |
| 3.8.0 | 128 | 11/2/2026 |
| 3.7.1 | 173 | 10/22/2026 |
| 3.7.0 | 322 | 10/5/2026 |
| 3.6.1 | 112 | 10/5/2026 |
| 3.6.0 | 115 | 10/2/2026 |
| 3.5.1 | 147 | 9/27/2026 |
| 3.5.0 | 110 | 9/27/2026 |
| 3.4.7 | 119 | 9/26/2026 |
| 3.4.6 | 155 | 9/7/2026 |
| 3.4.5 | 130 | 8/27/2026 |
| 3.4.4 | 135 | 8/22/2026 |
| 3.4.3 | 142 | 8/10/2026 |
- Takes Kanject.Core.Api.Abstractions 4.3.0.