AspNetCoreResponseKit 1.0.0

dotnet add package AspNetCoreResponseKit --version 1.0.0
                    
NuGet\Install-Package AspNetCoreResponseKit -Version 1.0.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="AspNetCoreResponseKit" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="AspNetCoreResponseKit" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="AspNetCoreResponseKit" />
                    
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 AspNetCoreResponseKit --version 1.0.0
                    
#r "nuget: AspNetCoreResponseKit, 1.0.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 AspNetCoreResponseKit@1.0.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=AspNetCoreResponseKit&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=AspNetCoreResponseKit&version=1.0.0
                    
Install as a Cake Tool

AspNetCoreResponseKit

NuGet Publish to NuGet License: MIT GitHub Sponsors Changelog

Standardized API response envelope and global exception handling middleware for ASP.NET Core. Smart factory methods, automatic exception-to-status-code mapping, and native integration with AspNetCoreAuthKit and AspNetCoreHttpKit.

Why AspNetCoreResponseKit? Every project writes the same ApiResponse class and the same ExceptionHandlerMiddleware. AspNetCoreResponseKit gives you a production-ready implementation with zero boilerplate, consistent error formats, and smart factories that eliminate try/catch blocks in controllers.


✨ Features

  • πŸ“¦ ApiResponse<T> β€” consistent response envelope for all endpoints
  • 🧠 Smart factories β€” ApiResponse.From(value) and ApiResponse.FromAsync(() => ...) handle null and errors automatically
  • 🌐 Middleware β€” app.UseApiExceptionHandler() catches all unhandled exceptions globally
  • πŸ—ΊοΈ Automatic mapping β€” exceptions are mapped to HTTP status codes via a priority chain
  • πŸ”— AspNetCoreAuthKit integration β€” HttpServiceException, RefreshTokenException mapped automatically
  • πŸ”— AspNetCoreHttpKit integration β€” ApiResponse.From(HttpResult<T>) converts upstream results directly
  • βš™οΈ Configurable β€” null status code, upstream propagation, exception details, custom mappings

πŸ“‹ Requirements

Requirement Minimum version
.NET 9.0+
ASP.NET Core 9.0+

πŸš€ Installation

dotnet add package AspNetCoreResponseKit

🎯 Quick Start

1. Register services

// Program.cs
builder.Services.AddAspNetCoreResponseKit(opt =>
{
    opt.IncludeExceptionDetails    = builder.Environment.IsDevelopment();
    opt.NullResponseStatusCode     = HttpStatusCode.NotFound;
    opt.PropagateUpstreamStatusCodes = true;
    opt.DefaultErrorMessage        = "An unexpected error occurred.";
 
    // Custom exception mapping
    opt.MapException<MyDomainException>(ex => (HttpStatusCode.UnprocessableEntity, ex.Message));
});
 
// Must be first in the middleware pipeline
app.UseApiExceptionHandler();
app.UseAuthentication();
app.UseAuthorization();

2. Use in controllers

[HttpGet("{id}")]
public async Task<ApiResponse<UserDto>> GetUser(int id, CancellationToken ct)
{
    // Smart factory β€” returns 200 if found, configured null status code if not
    return await ApiResponse.FromAsync(() => _service.GetUserAsync(id), ct: ct);
}
 
[HttpPost]
public async Task<ApiResponse<UserDto>> CreateUser(CreateUserRequest req, CancellationToken ct)
{
    var user = await _service.CreateAsync(req, ct);
    return ApiResponse.Created(user.ToDto(), "User created successfully.");
}
 
[HttpDelete("{id}")]
public async Task<ApiResponse> DeleteUser(int id, CancellationToken ct)
{
    var deleted = await _service.DeleteAsync(id, ct);
    return ApiResponse.FromBool(deleted, "User deleted.", "User not found.");
}

3. Use in Minimal APIs

app.MapGet("/users/{id}", async (int id, IUserService svc, CancellationToken ct) =>
{
    var result = await ApiResponse.FromAsync(() => svc.GetUserAsync(id), ct: ct);
    return result.ToResult();
});

4. Use with AspNetCoreHttpKit

app.MapGet("/proxy/users/{id}", async (int id, IHttpService http, CancellationToken ct) =>
{
    var result = await http.GetAsync<UserDto>($"/users/{id}", ct);
 
    // Converts HttpResult<T> directly β€” status code propagated based on options
    return ApiResponse.FromHttpResult(result).ToResult();
});

πŸ“¦ Response format

Success

{
  "isSuccess": true,
  "data": { "id": 1, "name": "Simone" },
  "message": null,
  "errors": [],
  "statusCode": 200
}

Error

{
  "isSuccess": false,
  "data": null,
  "message": "User not found.",
  "errors": [],
  "statusCode": 404
}

πŸ—ΊοΈ Exception mapping priority chain

When an unhandled exception is caught by the middleware, it is resolved in this order:

  1. Custom mappings β€” registered via opt.MapException<T>()
  2. AspNetCoreAuthKit / AspNetCoreHttpKit β€” HttpServiceException, RefreshTokenException, etc.
  3. Standard .NET exceptions β€” ArgumentException, UnauthorizedAccessException, etc.
  4. Fallback β€” 500 Internal Server Error

Built-in mappings

Exception Status code
HttpNotFoundException 404
HttpUnauthorizedException 401
HttpForbiddenException 403
HttpBadRequestException 400
HttpConflictException 409
HttpUnprocessableEntityException 422
HttpTooManyRequestsException 429
HttpServerErrorException 500+
RefreshTokenException 401
ArgumentNullException 400
ArgumentException 400
UnauthorizedAccessException 401
KeyNotFoundException 404
InvalidOperationException 409
NotImplementedException 501
TimeoutException 408
OperationCanceledException 499

πŸ“š API Reference

ApiResponse factory methods

Method Description
ApiResponse.Ok(data) 200 with data
ApiResponse.Created(data) 201 with data
ApiResponse.NoContent() 204
ApiResponse.NotFound<T>(message) 404
ApiResponse.BadRequest<T>(message) 400
ApiResponse.Unauthorized<T>(message) 401
ApiResponse.Forbidden<T>(message) 403
ApiResponse.Conflict<T>(message) 409
ApiResponse.Error(message, statusCode) Custom error
ApiResponse.From(value) Smart β€” null β†’ configured status code
ApiResponse.FromAsync(factory) Smart async β€” null β†’ configured status code
ApiResponse.FromBool(bool, onTrue, onFalse) Bool-based result
ApiResponse.From(HttpResult<T>) From AspNetCoreHttpKit result

ApiResponse<T> fluent methods

Method Description
.OnNull(message, statusCode?) Override response when data is null
.OnSuccess(transform) Transform data on success
.ToResult() Convert to IResult for Minimal APIs

βš™οΈ Configuration options

Option Type Default Description
NullResponseStatusCode HttpStatusCode 404 Status code when smart factory receives null
NullResponseMessage string "Resource not found." Message when smart factory receives null
PropagateUpstreamStatusCodes bool true Propagate status codes from upstream HTTP calls
IncludeExceptionDetails bool false Include exception message and stack trace in errors
DefaultErrorMessage string "An unexpected error occurred." Fallback error message

❀️ Support

If you find AspNetCoreResponseKit useful, consider sponsoring its development.

Sponsor simoneM93


πŸ“„ License

MIT β€” see LICENSE for details.

Product 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

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
1.0.0 36 3/31/2026