Rkd.Problems 1.0.0

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

Rkd.Problems - RFC 9457 Problem Details for HttpClient

<p align="center"> <img src="https://raw.githubusercontent.com/rkdcoder/Rkd.Problems/master/src/Rkd.Problems/Media/icon.png" width="128" alt="Rkd.Problems logo" /> </p>

NuGet Build & Publish License: MIT

Rkd.Problems is the client side of the error contract produced by Rkd.Scalar: it reads any error response of an HttpClient into one HttpProblem — status, stable code, title, detail, traceId and validation errors — so the client has a single error path, whatever answered the request: your API, plain ASP.NET Core, another API, a proxy or IIS.

using Rkd.Problems;

using var response = await http.GetAsync($"orders/{id}", ct);

if (await response.ReadProblemAsync(ct) is { } problem)
    return problem.Code switch
    {
        "ORDER_NOT_FOUND" => ShowNotFound(),
        ProblemCodes.Validation => ShowErrors(problem.Errors),
        _ => ShowError(problem.Detail ?? problem.Title)
    };

Core Features

  • HttpProblem with Status, Type, Title, Detail, Instance, Code, TraceId, Errors (IReadOnlyDictionary<string, string[]>) and Extensions (every other member, as JsonElement)
  • ReadProblemAsync() — the problem of an error response, null for a successful one
  • EnsureSuccessOrThrowProblemAsync() — EnsureSuccessStatusCode() that throws HttpProblemException (an HttpRequestException) with the problem, the status and Message = detail (or title)
  • Never fails on non-standard responses — application/json instead of application/problem+json, no code, empty body, plain text, HTML pages of proxies and IIS, invalid JSON: all become an HttpProblem
  • Code and Title are never null — derived from the status exactly as Rkd.Scalar does (NOT_FOUND, BAD_GATEWAY…)
  • Immune to JSON naming policies — code, traceId and errors are read by their contract names, whatever the naming policy (camelCase, snake_case…) of the server's DTOs or of your client
  • The shared contract — ProblemMembers, ProblemCodes and HttpProblem.MediaType are the constants Rkd.Scalar itself uses to write the errors: server and clients read the same definitions from one place
  • Runs everywhere — Blazor WebAssembly, Blazor Server, WPF / WinForms / MAUI, console apps and MCP servers, ASP.NET Core backends calling other APIs
  • No dependencies — no ASP.NET Core, only the BCL (System.Net.Http, System.Text.Json); trimmable and AOT compatible (no reflection, source generated JSON), with no API unsupported in the browser

Everything lives in one namespace: using Rkd.Problems;.


Installation

dotnet add package Rkd.Problems

Requires .NET 10. Servers using Rkd.Scalar 2.5+ already reference it.


The Contract

What Rkd.Scalar sends for every error (throw RkdError.NotFound("ORDER_NOT_FOUND", …), unhandled exceptions, validation, 401/403/404/405…):

HTTP/1.1 404 Not Found
Content-Type: application/problem+json

{
  "type": "https://tools.ietf.org/html/rfc9110#section-15.5.5",
  "title": "Not Found",
  "status": 404,
  "detail": "Order 42 was not found.",
  "instance": "/api/v1/orders/42",
  "code": "ORDER_NOT_FOUND",
  "traceId": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
}
Member HttpProblem When missing
status Status the status of the HTTP response
type Type null
title Title the status reason phrase (Not Found, Bad Gateway…)
detail Detail null
instance Instance null
code Code VALIDATION_ERROR when there are errors, otherwise the status in UPPER_SNAKE (NOT_FOUND)
traceId TraceId null
errors Errors empty
others Extensions empty

Validation problems carry the messages by field:

{
  "title": "One or more validation errors occurred.",
  "status": 400,
  "errors": { "email": ["Invalid e-mail."], "document": ["Required.", "Invalid format."] },
  "code": "VALIDATION_ERROR",
  "traceId": "00-…"
}

Non-standard responses

Clients do not choose who answers: a gateway times out, IIS returns its HTML page, another API sends { "message": "…" }. ReadProblemAsync never throws for the body format:

Response HttpProblem
application/problem+json (Rkd.Scalar) every member
problem without code (plain ASP.NET Core) members read, Code derived (VALIDATION_ERROR or from the status)
application/json instead of problem+json read the same way; unknown members (message, error…) in Extensions
empty body, text, HTML (nginx, IIS, load balancer) Status, Title = reason phrase, Code from the status
invalid JSON, JSON array / string / number same as above
connection dropped while reading the body same as above (the read error becomes the InnerException of HttpProblemException)

The default code follows the status reason phrase: 400 BAD_REQUEST, 401 UNAUTHORIZED, 403 FORBIDDEN, 404 NOT_FOUND, 409 CONFLICT, 413 PAYLOAD_TOO_LARGE, 422 UNPROCESSABLE_ENTITY, 429 TOO_MANY_REQUESTS, 500 INTERNAL_SERVER_ERROR, 502 BAD_GATEWAY, 503 SERVICE_UNAVAILABLE, 504 GATEWAY_TIMEOUT; unknown statuses become HTTP_{status}. ProblemCodes.FromStatus(status) returns it.

Member names are compared exactly as the contract writes them. Rkd.Scalar never renames them — even with WithJsonNaming(JsonNamingPolicy.SnakeCaseLower) the member is traceId, while the field names inside errors follow the server's policy (unit_price). Extensions also keeps known members whose value has an unexpected type ("code": 1001), so nothing the server sent is lost.


Reading Errors

ReadProblemAsync

using var response = await http.PostAsJsonAsync("customers", customer, ct);

var problem = await response.ReadProblemAsync(ct);   // null when 2xx

if (problem is null)
    return await response.Content.ReadFromJsonAsync<Customer>(ct);

EnsureSuccessOrThrowProblemAsync

Drop-in replacement for EnsureSuccessStatusCode(); returns the same response for chaining:

using var response = await http.GetAsync($"customers/{id}", ct);
await response.EnsureSuccessOrThrowProblemAsync(ct);

return await response.Content.ReadFromJsonAsync<Customer>(ct);
try
{
    await CreateCustomerAsync(customer, ct);
}
catch (HttpProblemException ex) when (ex.Problem.Code == "CUSTOMER_ALREADY_EXISTS")
{
    warning = ex.Message;                  // the detail sent by the server
}
catch (HttpProblemException ex)
{
    logger.LogWarning("Request failed: {Problem} (traceId {TraceId})", ex.Problem, ex.Problem.TraceId);
    error = ex.Message;                    // detail, or title when there is no detail
}

HttpProblemException derives from HttpRequestException: StatusCode is the HTTP status of the response, and existing catch (HttpRequestException) blocks keep working.

Extensions

Any other member sent by the server:

// { "code": "CREDIT_LIMIT_EXCEEDED", "limit": 5000.00, "available": 120.50, … }
if (problem.Extensions.TryGetValue("available", out var available))
    ShowAvailable(available.GetDecimal());

Share the codes

Keep the codes of your API as constants in a project shared by the server and its clients:

public static class CustomerErrors
{
    public const string NotFound = "CUSTOMER_NOT_FOUND";
    public const string AlreadyExists = "CUSTOMER_ALREADY_EXISTS";
}

// server (Rkd.Scalar)
throw RkdError.Conflict(CustomerErrors.AlreadyExists, "A customer with this document already exists.");

// client (Rkd.Problems)
catch (HttpProblemException ex) when (ex.Problem.Code == CustomerErrors.AlreadyExists) { … }

Examples

Blazor WebAssembly

The same code runs in Blazor WebAssembly, Blazor Server and WPF / MAUI with BlazorWebView.

// Program.cs
builder.Services.AddHttpClient<CustomersClient>(http => http.BaseAddress = new Uri("https://api.example.com/"));
public sealed class CustomersClient(HttpClient http)
{
    public async Task<Customer> CreateAsync(NewCustomer customer, CancellationToken ct = default)
    {
        using var response = await http.PostAsJsonAsync("customers", customer, ct);
        await response.EnsureSuccessOrThrowProblemAsync(ct);

        return (await response.Content.ReadFromJsonAsync<Customer>(ct))!;
    }
}

Validation errors go straight to the form fields:

@inject CustomersClient Customers

<EditForm EditContext="_edit" OnValidSubmit="SaveAsync">
    <DataAnnotationsValidator />
    <InputText @bind-Value="_customer.Email" />
    <ValidationMessage For="() => _customer.Email" />
    <InputText @bind-Value="_customer.Document" />
    <ValidationMessage For="() => _customer.Document" />

    @if (_error is not null)
    {
        <div class="alert alert-danger">@_error</div>
    }

    <button type="submit">Save</button>
</EditForm>

@code {
    private readonly NewCustomer _customer = new();
    private EditContext _edit = null!;
    private ValidationMessageStore _messages = null!;
    private string? _error;

    protected override void OnInitialized()
    {
        _edit = new EditContext(_customer);
        _messages = new ValidationMessageStore(_edit);
        _edit.OnValidationRequested += (_, _) => _messages.Clear();
        _edit.OnFieldChanged += (_, e) => _messages.Clear(e.FieldIdentifier);
    }

    private async Task SaveAsync()
    {
        _error = null;

        try
        {
            await Customers.CreateAsync(_customer);
        }
        catch (HttpProblemException ex) when (ex.Problem.Errors.Count > 0)
        {
            // Field names are the JSON names sent by the server ("email", "document").
            foreach (var (field, messages) in ex.Problem.Errors)
                _messages.Add(_edit.Field(ToPropertyName(field)), messages);

            _edit.NotifyValidationStateChanged();
        }
        catch (HttpProblemException ex)
        {
            _error = ex.Message;
        }
    }

    private static string ToPropertyName(string field) =>
        field.Length == 0 ? field : char.ToUpperInvariant(field[0]) + field[1..];
}

Console apps and MCP servers

using var http = new HttpClient { BaseAddress = new Uri("https://api.example.com/") };

try
{
    using var response = await http.GetAsync("orders/42");
    await response.EnsureSuccessOrThrowProblemAsync();

    Console.WriteLine(await response.Content.ReadAsStringAsync());
}
catch (HttpProblemException ex)
{
    Console.Error.WriteLine($"{ex.Problem} (traceId {ex.Problem.TraceId})");   // 404 ORDER_NOT_FOUND: Order 42 was not found.
    return 1;
}

An MCP tool can hand the model the stable code and the message instead of a generic failure (ModelContextProtocol SDK):

[McpServerToolType]
public sealed class OrderTools(HttpClient http)
{
    [McpServerTool, Description("Gets an order by id.")]
    public async Task<string> GetOrder(int id, CancellationToken ct)
    {
        using var response = await http.GetAsync($"orders/{id}", ct);

        if (await response.ReadProblemAsync(ct) is { } problem)
            throw new McpException($"{problem.Code}: {problem.Detail ?? problem.Title}");

        return await response.Content.ReadAsStringAsync(ct);
    }
}

ASP.NET Core backends calling other APIs

A typed client translates the upstream errors it knows and lets the rest become a 502:

builder.Services.AddHttpClient<PaymentsClient>(http => http.BaseAddress = new Uri("https://payments.internal/"));
public sealed class PaymentsClient(HttpClient http, ILogger<PaymentsClient> logger)
{
    public async Task<Payment> ChargeAsync(Charge charge, CancellationToken ct)
    {
        using var response = await http.PostAsJsonAsync("charges", charge, ct);

        if (await response.ReadProblemAsync(ct) is not { } problem)
            return (await response.Content.ReadFromJsonAsync<Payment>(ct))!;

        // Upstream business errors keep their code for your own clients (Rkd.Scalar RkdError)…
        if (problem.Code is "CARD_DECLINED" or "INSUFFICIENT_FUNDS")
            throw RkdError.UnprocessableEntity(problem.Code, problem.Detail);

        // …anything else is logged with the upstream traceId and never exposed.
        logger.LogError("Payments failed: {Problem} (upstream traceId {TraceId})", problem, problem.TraceId);
        throw RkdError.Create(StatusCodes.Status502BadGateway, "PAYMENTS_UNAVAILABLE", "The payment provider is unavailable.")
            .WithLogDetails(problem.ToString());
    }
}

Without Rkd.Scalar, use EnsureSuccessOrThrowProblemAsync() and handle HttpProblemException in your exception handler the same way.


The Shared Contract

Rkd.Scalar references Rkd.Problems and writes the errors with these constants, so the server and every client read the contract from one place:

Constant Value
ProblemMembers.Code code
ProblemMembers.TraceId traceId
ProblemMembers.Errors errors
ProblemMembers.Type / Title / Status / Detail / Instance the RFC 9457 members
ProblemCodes.Validation VALIDATION_ERROR
ProblemCodes.FromStatus(404) NOT_FOUND
HttpProblem.MediaType application/problem+json

Trimming, AOT and WebAssembly

The package is built with IsTrimmable, IsAotCompatible and the browser platform analyzer, with warnings as errors: it uses no reflection (the JSON is read through a source generated JsonSerializerContext), no API that is unsupported in the browser, and never your application's JsonSerializerOptions.


Compatibility

Component Version
.NET 10.0
Rkd.Scalar 2.3+ (servers producing the contract; 2.5+ reference this package)
Dependencies none (BCL only)

Contributing

Pull requests and issues are welcome.


License

MIT License.

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

    • No dependencies.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on Rkd.Problems:

Package Downloads
Rkd.Scalar

Zero-boilerplate Scalar wrapper for ASP.NET Core. Configures OpenAPI, API Versioning and Authentication (JWT with HMAC, RSA, ECDSA, OIDC/JWKS or async/KMS signing, Basic, API Key) in a few fluent lines, applies XML documentation comments automatically, standardizes errors as RFC 9457 problem details, with built-in documentation UI protection, a development login endpoint and configuration-based validators.

Rkd.Scalar.Errors

Errors of Rkd.Scalar for any layer (Domain, Application, Infrastructure): RkdError, ProblemException and IProblemLogDetails (namespace Rkd.Scalar: using Rkd.Scalar;), converted into RFC 9457 problem details by WithProblemDetails() in the API project. Depends only on Rkd.Problems and the ASP.NET Core shared framework (no other package).

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0 464 9/30/2026