.NET Development

Problem Details in ASP.NET Core 10: consistent API errors, measured

Team Nippysoft
• • 19 min read
Problem Details in ASP.NET Core 10: consistent API errors, measured

Pool Rivera recently made a point on LinkedIn: an HTTP error is part of your API's contract. Comparing Results.NotFound(new { message }) with Results.Problem(...), the post concluded that using Results.Problem() alone doesn't guarantee consistent errors, and that consistency takes a common strategy, defined and applied on purpose. I agree, and this article adds two things to that post: what ASP.NET Core 10 actually returns for each kind of error, and a common strategy you can copy, with its measured results.

I built the same API with three error setups and sent it 14 baseline requests (an unknown route, exceptions, malformed JSON, invalid fields, a client that asks for HTML and more) in Production and in Development, recording the status code, Content-Type, body and logs. Three results set the tone: a new app with no setup returns 404, 405 and 500 with no body and accepts invalid data with a 201; the documented recipe fixes almost everything but leaves a custom error body alone; and the same malformed JSON gets a 400 in Production and a 500 in Development. Everything here is .NET 10.0.14 (SDK 10.0.403) on Kestrel over HTTP, on Windows 11.

What RFC 9457 asks for

The current standard is RFC 9457, from July 2023, which replaces RFC 7807 ("Obsoletes: 7807"). An error response uses the application/problem+json media type and up to five members:

  • type: a URI that identifies the problem type. When it's missing, "its value is assumed to be "about:blank"".
  • status: the HTTP status code, for information only. It has to match the real one: "Generators MUST use the same status code in the actual HTTP response".
  • title: a short summary of the problem type.
  • detail: the explanation for this occurrence, which "ought to focus on helping the client correct the problem, rather than giving debugging information".
  • instance: a reference to this specific occurrence.

Anything else is an extension, and the RFC protects older clients: "Clients consuming problem details MUST ignore any such extensions that they don't recognize".

Pool is right: NotFound isn't wrong in itself. The RFC itself says generic problems "are usually better expressed as plain status codes". The trouble starts when one API mixes shapes.

What an app with no setup returns

The 14 cases in Production with three setups: no error handling, the documented recipe, and this article's contract. The app has Minimal API endpoints and one [ApiController] controller.

CaseNo setupDocumented recipeThis post's contract
A. Unknown route404 · empty404 · Problem Details404 · Problem Details
B. Results.NotFound(new { message })404 · custom JSON404 · custom JSON404 · custom JSON
C. Results.Problem(title, detail, 404)404 · Problem Details404 · Problem Details404 · Problem Details
D. Empty Results.NotFound()404 · empty404 · Problem Details404 · Problem Details
E. Domain exception500 · empty500 · Problem Details404 · Problem Details
F. Any other exception500 · empty500 · Problem Details500 · Problem Details
G. F with Accept: text/html500 · empty500 · empty500 · empty
H. A with Accept: text/html404 · empty404 · plain text404 · plain text
I. Method not allowed405 · empty405 · Problem Details405 · Problem Details
J. Invalid fields (Minimal API)201 · created resource201 · created resource400 · Problem Details
K. Malformed JSON400 · empty400 · Problem Details400 · Problem Details
L. text/plain415 · empty415 · Problem Details415 · Problem Details
M. Invalid fields ([ApiController])400 · Problem Details400 · Problem Details400 · Problem Details
N. NotFound() in [ApiController]404 · Problem Details404 · Problem Details404 · Problem Details

With no setup, nine of the 14 cases come back with no body: 404, 405, 400, 415 and 500. The invalid fields in case J are accepted with a 201, because without AddValidation() Minimal APIs don't check [Required] or [Range].

In the same app, the controller already answers M and N with Problem Details. The documentation explains it: "The automatic creation of a ProblemDetails for error status codes is enabled by default." So a brand new app already returns errors in two shapes nobody chose.

Case C changes too: Results.Problem fills in the RFC 9110 type (it comes from ProblemDetailsDefaults), but traceId only shows up with AddProblemDetails. With no setup and with the recipe:

-- C. Results.Problem(title, detail, 404)
   404 | application/problem+json | 133 bytes
   body: {"type":"https://tools.ietf.org/html/rfc9110#section-15.5.5","title":"User not found","status":404,"detail":"User 7 does not exist."}
-- C. Results.Problem(title, detail, 404)
   404 | application/problem+json | 201 bytes
   body: {"type":"https://tools.ietf.org/html/rfc9110#section-15.5.5","title":"User not found","status":404,"detail":"User 7 does not exist.","traceId":"<masked>"}

The documented recipe, and the body it leaves alone

The guide Handle errors in ASP.NET Core APIs suggests three calls:

builder.Services.AddProblemDetails();
// ...
app.UseExceptionHandler();
app.UseStatusCodePages();

With them, A, D, I, K and L switch to application/problem+json with type, title, status and traceId. Exceptions (E and F) become a 500 titled "An error occurred while processing your request." with no internal message.

Two things stay broken. One is case B: {"message":"User not found"} comes out the same in every setup. The documentation says why: the middleware produces Problem Details for error responses "that don't have body content yet". A custom body already has content, so nothing rewrites it. That's why Pool's common strategy also needs a team rule: don't return custom error bodies.

The other is the domain exception (E). The endpoint throws ResourceNotFoundException and the client gets a generic 500, because the middleware has no way of knowing that "doesn't exist" means 404.

Search your code for Results.NotFound(new, Results.BadRequest(new and the like. Each one is an error with its own shape that no middleware will normalize.

The same malformed JSON: 400 in Production, 500 in Development

With the documented recipe, request K (a JSON body cut in half) gets two different answers depending on the environment:

-- K. POST malformed JSON (Minimal API)
   400 | application/problem+json | 164 bytes
   body: {"type":"https://tools.ietf.org/html/rfc9110#section-15.5.1","title":"Bad Request","status":400,"traceId":"<masked>"}
-- K. POST malformed JSON (Minimal API)
   500 | application/problem+json | 201 bytes
   body: {"type":"https://tools.ietf.org/html/rfc9110#section-15.6.1","title":"An error occurred while processing your request.","status":500,"traceId":"<masked>"}
   log: Error ExceptionHandlerMiddleware: An unhandled exception has occurred while executing the request.

The cause is documented: "In the Development environment, ThrowOnBadRequest defaults to true", so the read failure is thrown as a BadHttpRequestException. Outside Development it's false, and the 400 is written directly, "bypassing custom exception handlers". Once the exception reaches the middleware, it becomes a 500: "In ASP.NET Core 10 and earlier, unhandled exceptions default to 500 Internal Server Error unless the handler explicitly preserves BadHttpRequestException.StatusCode on both HttpContext.Response.StatusCode and the generated Status." The ExceptionHandlerMiddlewareImpl source confirms it: StatusCodeSelector?.Invoke(...) ?? DefaultStatusCode, with DefaultStatusCode set to 500.

Whoever tests in Development sees a 500 where Production will send a 400. The fix is ThrowOnBadRequest = true in every environment plus a handler that keeps BadHttpRequestException.StatusCode. Measured: 400 in both.

The common strategy, in one method

The contract fits in one extension method. It sets instance to the request path when nobody set it, registers the handler, turns on .NET 10 validation and makes read failures behave the same in every environment:

namespace ProblemDetailsLab;

public static class ErrorContract
{
    // The error contract of the post, in one place.
    public static IServiceCollection AddErrorContract(this IServiceCollection services)
    {
        services.AddProblemDetails(options =>
        {
            // RFC 9457 wants instance to identify this occurrence; the request path only names the resource.
            // The traceId extension is what tells occurrences apart.
            options.CustomizeProblemDetails = context =>
                context.ProblemDetails.Instance ??= context.HttpContext.Request.Path.ToUriComponent();
        });
        services.AddExceptionHandler<ProblemExceptionHandler>();
        services.AddValidation();
        // Same behavior in Development and Production: JSON binding failures always throw,
        // and ProblemExceptionHandler keeps the status code the binder chose.
        // Body read errors (such as 413) don't throw: the binder sets the status code itself.
        services.Configure<RouteHandlerOptions>(options => options.ThrowOnBadRequest = true);
        return services;
    }
}

The path in instance is a common shortcut, not what the RFC asks for: "a URI reference that identifies the specific occurrence of the problem". The path identifies the resource, so two failures on /boom get the same instance. What tells occurrences apart is traceId, which changes on every request.

The handler maps the exceptions it knows; for anything else it returns false and the middleware writes the generic 500:

using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;

namespace ProblemDetailsLab;

// Maps the exceptions we know to Problem Details. Unknown exceptions return false,
// so the middleware logs them and writes a generic 500 without internal details.
public sealed class ProblemExceptionHandler(
    IProblemDetailsService problemDetailsService,
    ILogger<ProblemExceptionHandler> logger) : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(
        HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
    {
        ProblemDetails? problem = exception switch
        {
            ResourceNotFoundException notFound => new()
            {
                Status = StatusCodes.Status404NotFound,
                Type = "https://errors.example.com/problems/resource-not-found",
                Title = "Resource not found",
                Detail = notFound.Message,
                Extensions = { ["resource"] = notFound.Resource },
            },
            // Read failures the binder throws (malformed JSON, wrong JSON types, empty body): keep its status code.
            BadHttpRequestException badRequest => new()
            {
                Status = badRequest.StatusCode,
                Detail = "The request could not be read.",
            },
            _ => null,
        };

        if (problem is null)
            return false;

        // .NET 10 no longer logs exceptions that a handler reports as handled.
        // This line logs which exception was mapped (type and status), not the exception itself.
        logger.LogInformation("Mapped {ExceptionType} to {Status}", exception.GetType().Name, problem.Status);

        httpContext.Response.StatusCode = problem.Status!.Value;
        // TryWriteAsync returns false when no Accept value covers JSON (for example, Accept: text/html alone).
        // The status code is already right: report the exception as handled anyway.
        await problemDetailsService.TryWriteAsync(new()
        {
            HttpContext = httpContext,
            ProblemDetails = problem,
            Exception = exception,
        });
        return true;
    }
}

The documentation sets one condition: "An IExceptionHandler that returns true should write the complete response, including the status code." So the handler sets StatusCode before calling IProblemDetailsService.TryWriteAsync, which applies CustomizeProblemDetails and adds traceId. When no Accept value covers JSON, TryWriteAsync writes nothing and returns false; the handler returns true anyway, because the status code is already right. The errors.example.com domain is a placeholder: use one your team owns.

In Program.cs the pipeline is the same in every environment, without the if (!app.Environment.IsDevelopment()) from the variant in the error handling guide. No UseExceptionHandler, no handler: "If UseExceptionHandler isn't called, the registered IExceptionHandler implementations are never called."

using ProblemDetailsLab;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddErrorContract();

var app = builder.Build();

// In every environment: the same error rules in Development and Production.
app.UseExceptionHandler();
app.UseStatusCodePages();

Endpoints.Map(app);
app.Run();

The test endpoints and the controller:

using System.ComponentModel.DataAnnotations;

namespace ProblemDetailsLab;

public sealed record User(int Id, string Name);

public sealed record CreateUserRequest(
    [Required, StringLength(50, MinimumLength = 2)] string Name,
    [Range(18, 120)] int Age);

public sealed class ResourceNotFoundException(string resource, object id)
    : Exception($"{resource} '{id}' does not exist.")
{
    public string Resource { get; } = resource;
}

// The same endpoints are mapped in every profile, so only the error setup changes.
public static class Endpoints
{
    public static void Map(WebApplication app)
    {
        // Ad hoc body, like the "message" example in the LinkedIn post.
        app.MapGet("/v1/users/{id:int}", (int id) =>
            id == 1 ? Results.Ok(new User(1, "Ana")) : Results.NotFound(new { message = "User not found" }));

        // Results.Problem written by hand.
        app.MapGet("/v2/users/{id:int}", (int id) =>
            id == 1
                ? Results.Ok(new User(1, "Ana"))
                : Results.Problem(title: "User not found", detail: $"User {id} does not exist.", statusCode: 404));

        // Empty 404: the body is left to the middleware.
        app.MapGet("/v3/users/{id:int}", (int id) =>
            id == 1 ? Results.Ok(new User(1, "Ana")) : Results.NotFound());

        // Domain exception: the endpoint does not know about HTTP errors at all.
        app.MapGet("/v4/users/{id:int}", (int id) =>
            id == 1 ? Results.Ok(new User(1, "Ana")) : throw new ResourceNotFoundException("User", id));

        app.MapPost("/v1/users", (CreateUserRequest request) =>
            Results.Created($"/v1/users/2", new User(2, request.Name)));

        app.MapGet("/boom", () =>
        {
            throw new InvalidOperationException("Orders database timed out after 30 s (internal detail).");
        });

        app.MapControllers();
    }
}
using Microsoft.AspNetCore.Mvc;

namespace ProblemDetailsLab;

// A controller in the same app: [ApiController] has its own automatic 400 response.
[ApiController]
[Route("api/users")]
public sealed class UsersController : ControllerBase
{
    [HttpPost]
    public IActionResult Create(CreateUserRequest request) =>
        Created("/api/users/2", new User(2, request.Name));

    [HttpGet("{id:int}")]
    public IActionResult Get(int id) =>
        id == 1 ? Ok(new User(1, "Ana")) : NotFound();
}
Who writes the error body with this post's contract Who writes the error body with this post's contract The endpoint Who writes the body Response Results.NotFound(new { message }) nobody: it has a body 404 · custom JSON Results.NotFound() UseStatusCodePages 404 · Problem Details throw ResourceNotFoundException ProblemExceptionHandler 404 · resource-not-found throw InvalidOperationException handler: false → middleware 500 · generic

The result is the same in Production and Development (Kestrel over HTTP, Windows 11): A, C, D, E, F, I, J, K, L, M and N come back as application/problem+json with instance (the path, not the occurrence) and traceId. The traceId changes on every request, so it's shown as <masked>. The domain exception is now a 404 with its own type, and the unknown one is still a 500 with no internal message:

-- E. throw ResourceNotFoundException
   404 | application/problem+json | 254 bytes
   body: {"type":"https://errors.example.com/problems/resource-not-found","title":"Resource not found","status":404,"detail":"User '7' does not exist.","instance":"/v4/users/7","resource":"User","traceId":"<masked>"}
   log: Information ProblemExceptionHandler: Mapped ResourceNotFoundException to 404
-- F. throw InvalidOperationException
   500 | application/problem+json | 220 bytes
   body: {"type":"https://tools.ietf.org/html/rfc9110#section-15.6.1","title":"An error occurred while processing your request.","status":500,"instance":"/boom","traceId":"<masked>"}
   log: Error ExceptionHandlerMiddleware: An unhandled exception has occurred while executing the request.
-- K. POST malformed JSON (Minimal API)
   400 | application/problem+json | 229 bytes
   body: {"type":"https://tools.ietf.org/html/rfc9110#section-15.5.1","title":"Bad Request","status":400,"detail":"The request could not be read.","instance":"/v1/users","traceId":"<masked>"}
   log: Information ProblemExceptionHandler: Mapped BadHttpRequestException to 400

B stays out, with its custom body. A client that asks only for HTML gets the right status code from the contract, but no Problem Details.

To try it with SDK 10.0.403:

dotnet new web -n ProblemDetailsLab
# copy the post's five .cs files into ProblemDetailsLab/ (Program.cs replaces the template's)
dotnet run --project ProblemDetailsLab --urls http://localhost:5327
curl -i http://localhost:5327/v4/users/7
If your handler returns true, set StatusCode, write the body and decide what to log yourself: the middleware writes nothing and, since .NET 10, doesn't log the exception either.

Validation: AddValidation and [ApiController] don't return the same list

.NET 10 brings built-in validation to Minimal APIs through AddValidation(). According to What's new in ASP.NET Core in .NET 10, "If validation fails, the runtime returns a 400 Bad Request response with details of the validation errors", and, for clients that accept JSON, those responses go through the app's IProblemDetailsService. Here is the same body, {"name":"","age":7}, sent to the Minimal API and to the controller:

-- J. POST invalid fields (Minimal API)
   400 | application/problem+json | 317 bytes
   body: {"type":"https://tools.ietf.org/html/rfc9110#section-15.5.1","title":"One or more validation errors occurred.","status":400,"instance":"/v1/users","errors":{"Name":["The Name field is required."],"Age":["The field Age must be between 18 and 120."]},"traceId":"<masked>"}
-- M. POST invalid fields ([ApiController])
   400 | application/problem+json; charset=utf-8 | 407 bytes
   body: {"type":"https://tools.ietf.org/html/rfc9110#section-15.5.1","title":"One or more validation errors occurred.","status":400,"instance":"/api/users","errors":{"Age":["The field Age must be between 18 and 120."],"Name":["The Name field is required.","The field Name must be a string with a minimum length of 2 and a maximum length of 50."]},"traceId":"<masked>"}

The Minimal API returns one error per field; [ApiController] returns every failing rule, in a different order. I didn't look for the cause in the validator code. In practice, a client or a test that depends on how many messages there are, or their order, will see different answers depending on the kind of endpoint. Problem Details makes the format uniform, not the content.

Malformed JSON doesn't match either. Against the controller (extra case T), the 400 skips our handler: it's the automatic [ApiController] response, with the JSON reader's message inside errors:

-- T. POST malformed JSON ([ApiController])
   400 | application/problem+json; charset=utf-8 | 396 bytes
   body: {"type":"https://tools.ietf.org/html/rfc9110#section-15.5.1","title":"One or more validation errors occurred.","status":400,"instance":"/api/users","errors":{"request":["The request field is required."],"$.name":["Expected end of string, but instead reached end of data. Path: $.name | LineNumber: 0 | By..."]},"traceId":"<masked>"}

The Minimal API only gives the handler's generic detail. The contract doesn't change how MVC reports read failures.

Watch out with record types: with the attributes on the property ([property: Range(18, 120)] int Age), the controller answered with a 500 and an InvalidOperationException. On the parameter, as in CreateUserRequest, both kinds of endpoint work.

The client that asks for text/html

The default writer only writes Problem Details when the Accept header is missing or one of its values covers application/json or application/problem+json, wildcards included and ignoring the q quality (DefaultProblemDetailsWriter). The guide warns about it: "Non-JSON media types, such as application/xml or text/html, are not supported and trigger the fallback behavior." With Accept: text/html, an unknown exception gets a 500 with an empty body, even with the contract. An unknown route gets a 404 in text/plain.

-- G. throw InvalidOperationException, Accept: text/html
   500 | (none) | 0 bytes
   body: (empty)
   log: Error ExceptionHandlerMiddleware: An unhandled exception has occurred while executing the request.
-- H. GET unknown route, Accept: text/html
   404 | text/plain | 527 bytes
   body: Status Code: 404; Not Found

The domain exception and the malformed JSON (extra cases O and P, measured separately, outside the table's 14) keep their 404 and 400, with no body either:

-- O. throw ResourceNotFoundException, Accept: text/html
   404 | (none) | 0 bytes
   body: (empty)
   log: Information ProblemExceptionHandler: Mapped ResourceNotFoundException to 404
-- P. POST malformed JSON, Accept: text/html
   400 | (none) | 0 bytes
   body: (empty)
   log: Information ProblemExceptionHandler: Mapped BadHttpRequestException to 400

Edge 156 (headless) sends Accept: text/html,...,*/*;q=0.8, and */* covers JSON: opened in Edge, /v4/users/7 shows the 404 as Problem Details. With that header (Q and R), and with application/json;q=0, text/html (S), which refuses JSON and still gets it:

-- Q. throw InvalidOperationException, browser Accept
   500 | application/problem+json | 220 bytes
   body: {"type":"https://tools.ietf.org/html/rfc9110#section-15.6.1","title":"An error occurred while processing your request.","status":500,"instance":"/boom","traceId":"<masked>"}
   log: Error ExceptionHandlerMiddleware: An unhandled exception has occurred while executing the request.
-- R. throw ResourceNotFoundException, browser Accept
   404 | application/problem+json | 254 bytes
   body: {"type":"https://errors.example.com/problems/resource-not-found","title":"Resource not found","status":404,"detail":"User '7' does not exist.","instance":"/v4/users/7","resource":"User","traceId":"<masked>"}
   log: Information ProblemExceptionHandler: Mapped ResourceNotFoundException to 404
-- S. throw ResourceNotFoundException, Accept: application/json;q=0, text/html
   404 | application/problem+json | 254 bytes
   body: {"type":"https://errors.example.com/problems/resource-not-found","title":"Resource not found","status":404,"detail":"User '7' does not exist.","instance":"/v4/users/7","resource":"User","traceId":"<masked>"}
   log: Information ProblemExceptionHandler: Mapped ResourceNotFoundException to 404

G, H, O and P only happen with an Accept header that has no JSON and no wildcard.

Logs in .NET 10: what the handler handles, the middleware no longer logs

This is a .NET 10 breaking change: "Starting in .NET 10, if IExceptionHandler.TryHandleAsync returns true, then exception diagnostics are no longer recorded by default." That covers the UnhandledException log and the error.type tag on the http.server.request.duration metric. I didn't measure the metric; I did measure the logs.

You can see it in the E and F output above: the domain exception only leaves our handler's Information line; the unknown one leaves the middleware's Error.

If you want the .NET 8 and 9 behavior back, SuppressDiagnosticsCallback = _ => false in the UseExceptionHandler options restores it, and the domain exception also leaves the Error:

-- E. throw ResourceNotFoundException
   404 | application/problem+json | 254 bytes
   body: {"type":"https://errors.example.com/problems/resource-not-found","title":"Resource not found","status":404,"detail":"User '7' does not exist.","instance":"/v4/users/7","resource":"User","traceId":"<masked>"}
   log: Information ProblemExceptionHandler: Mapped ResourceNotFoundException to 404
   log: Error ExceptionHandlerMiddleware: An unhandled exception has occurred while executing the request.

Be careful when you copy the example from the .NET 10 release notes: it has a semicolon inside the object initializer and doesn't compile (error CS1003).

If a handler reports an exception as handled, logging it is the handler's job. ProblemExceptionHandler only logs which exception it mapped and to which status, without the exception or its stack trace; for a domain 404 that's enough. Debugging a read failure takes the exception: passed as the first argument (LogInformation(exception, ...)), the log for case K carries the BadHttpRequestException and, inside it, the JsonException with the position of the error.

What leaks in Development

With no setup, an exception in Development returns the stack trace as plain text:

-- F. throw InvalidOperationException
   500 | text/plain; charset=utf-8 | 791 bytes
   body: System.InvalidOperationException: Orders database timed out after 30 s (internal detail).
   log: Error DeveloperExceptionPageMiddleware: An unhandled exception has occurred while executing the request.

The variant in the error handling guide that only calls UseExceptionHandler outside Development lets the Developer Exception Page answer instead. When the client doesn't ask for text/html, that page responds in Problem Details format, with an exception extension that carries the stack trace, the path, the endpoint, the route values and every request header:

-- F. throw InvalidOperationException
   500 | application/problem+json | 1245 bytes
   body: {"type":"https://tools.ietf.org/html/rfc9110#section-15.6.1","title":"System.InvalidOperationException","status":500,"detail":"Orders database timed out after 30 s (internal detail).","exception":{"details":"System.InvalidOperationException: Orders database timed out after 30 s (internal detail).\r...","headers":{"Host":["localhost:5317"],"X-Probe":["visible-request-header"]},"path":"/boom","endpoint":"HTTP: GET /boom","routeValues":{}},"traceId":"<masked>"}
   log: Error DeveloperExceptionPageMiddleware: An unhandled exception has occurred while executing the request.

The test's X-Probe header comes back as sent, and the source shows why: headers: httpContext.Request.Headers. An Authorization or Cookie header would come back the same way. In Production, the same setup returns the generic 500.

The guide is clear: "Don't enable the Developer Exception Page unless the app is running in the Development environment." The rule: never run Development outside a developer's machine, and only put text meant for the client in detail.

Check ASPNETCORE_ENVIRONMENT on every shared environment. A test server running in Development without UseExceptionHandler hands stack traces and headers to anyone who calls it.

What the contract doesn't cover

Measured separately with the same code:

  • What Kestrel rejects before the app never reaches the pipeline: a 40,000-character header gets a 431, and an invalid Host a 400, both with no body (W and X).
  • A 31 MB body gets a 413 with Problem Details, but it skips the handler: no log line and no detail from it (V).
  • instance echoes the path as it came: /users/ana@example.com/reset/TOKEN123 comes back in the 404 (U). If your routes carry personal data or tokens, so does the error body.
  • If you add UsePathBase("/base"), /base/v4/users/7 gets "instance":"/v4/users/7", without the base, so that reference no longer points to the real place.

What isn't tested

  • I only tested Kestrel over HTTP on Windows. Not Linux, containers, IIS, HTTP/2 or HTTPS.
  • I didn't test 401, 403, 429, CORS or exceptions after the response has started.
  • The http.server.request.duration metric with error.type comes from the documentation, not from my runs.

Frequently asked questions

Do I have to replace every Results.NotFound() with Results.Problem()?

No. With AddProblemDetails and UseStatusCodePages, an empty Results.NotFound() already comes out as Problem Details (case D). What you need to remove are custom bodies like Results.NotFound(new { message }).

Why doesn't my IExceptionHandler run?

Most likely app.UseExceptionHandler() is missing, or it's only called outside Development. Without that call, registered handlers never run.

Can I put the exception message in detail?

Only if you wrote it for the client, like the one in ResourceNotFoundException. For an unknown exception, no: its message may carry internal details, and the RFC wants detail to help fix the problem, not to debug it.

Conclusion

Consistency doesn't happen by itself. A new app already mixes empty responses with Problem Details; the documented recipe lets custom bodies through and turns malformed JSON into a 500 in Development, and .NET 10 no longer logs what a handler reports as handled. The contract fixes that with one method, one handler and two pipeline lines, plus a team rule no code can replace: don't return custom error bodies.

If you already return some errors with Results.Problem, like the 422 in the idempotency key post, this contract makes the rest of your API's errors follow the same shape. Send requests A to N from the table to your API and compare.

References

Subscribe

Get the latest posts delivered right to your inbox.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Comments

No comments yet. Be the first to share your thoughts!

Subscribed!

Registered! A confirmation link has been sent to your email address. If you don't see it, please check your spam folder.

Error

An error occurred. Please try again.

Full code