skip to content

In ASP.NET Core 10, how do Results.Problem, Results.ValidationProblem and ControllerBase.ValidationProblem differ in body type, default status and errors?

level: middleimportance: should knowfreq 48%

answer

  1. ProblemDetails vs HttpValidationProblemDetails
  2. errors as IDictionary<string, string[]>
  3. 500 by default vs 400 by default
  4. TypedResults.ValidationProblem is fixed at 400
  5. ValidationProblemDetails built from ModelState

basics

~10 s

Results.Problem writes a ProblemDetails, 500 unless you pass a status. Results.ValidationProblem writes an HttpValidationProblemDetails with an errors dictionary, 400 by default. ControllerBase.ValidationProblem builds a ValidationProblemDetails from ModelState, also 400.

solid answer

~40 s

`Results.Problem(detail, instance, statusCode, title, type, extensions)` returns a `ProblemHttpResult` holding a plain `ProblemDetails`; with no status it uses 500, and the common statuses get a default `type` and `title`. `Results.ValidationProblem(errors, ...)` builds an `HttpValidationProblemDetails`, whose `errors` member is an `IDictionary<string, string[]>` and whose title defaults to "One or more validation errors occurred."; it is 400 unless you pass `statusCode`. `TypedResults.ValidationProblem` has no `statusCode` parameter: its `ValidationProblem` result is always 400. In a controller, `ValidationProblem()` with no arguments reads `ModelState` and asks `ProblemDetailsFactory` for a `ValidationProblemDetails` (MVC's subclass of `HttpValidationProblemDetails`), returned as a `BadRequestObjectResult`; `ControllerBase.Problem()` defaults to 500 the same way. All of them send `application/problem+json` by default.

code

csharp · 21 lines
csharp
[ApiController]
[Route("api/accounts")]
public class AccountsController : ControllerBase
{
    [HttpPost("{id:int}/freeze")]
    public IActionResult Freeze(int id, FreezeRequest request)
    {
        if (request.Reason.Length < 10)
        {
            ModelState.AddModelError(nameof(request.Reason), "Give at least 10 characters.");
            return ValidationProblem();              // 400, ValidationProblemDetails from ModelState
        }

        if (id == 7)
        {
            return Problem(statusCode: 409, detail: "Account 7 is already frozen.");
        }

        return NoContent();
    }
}

go deeper

for a junior

Recall the three types, that errors is a dictionary of string arrays, and that Problem defaults to 500 while ValidationProblem defaults to 400.

for a middle

Explain how the Minimal API helpers and the ControllerBase methods build their bodies, and why TypedResults.ValidationProblem is fixed at 400.

for a senior

Show you know what a hand-built ProblemDetails skips (ClientErrorMapping, traceId, customization) and how to return validation bodies with other statuses.

for a principal

Weigh one validation-body shape across controllers, Minimal APIs and hand-written checks, and decide where a team standardizes the status for rule failures.

## The three body types ASP.NET Core has one base class and two validation subclasses: - **`ProblemDetails`** (namespace `Microsoft.AspNetCore.Mvc`): `Type`, `Title`, `Status`, `Detail`, `Instance`, plus an `Extensions` dictionary flattened into the JSON. - **`HttpValidationProblemDetails`** (namespace `Microsoft.AspNetCore.Http`): adds **`Errors`**, an `IDictionary<string, string[]>` serialized as `errors`, keyed by field name with one or more messages per key. Its constructor sets the title to "One or more validation errors occurred." - **`ValidationProblemDetails`** (MVC): derives from `HttpValidationProblemDetails` and adds a constructor that turns a `ModelStateDictionary` into that dictionary, using "The input was not valid." for an error without a message. ## Minimal API helpers | Helper | Result type | Body | Default status | |---|---|---|---| | `Results.Problem(...)` / `TypedResults.Problem(...)` | `ProblemHttpResult` | `ProblemDetails` | 500 | | `Results.ValidationProblem(errors, ...)` | `ProblemHttpResult` | `HttpValidationProblemDetails` | 400, or the `statusCode` you pass | | `TypedResults.ValidationProblem(errors, ...)` | `ValidationProblem` | `HttpValidationProblemDetails` | always 400 | - `Problem` accepts `detail`, `instance`, `statusCode`, `title`, `type` and `extensions`; an overload takes a ready `ProblemDetails`. - When `Status` is null, the result fills it: 400 for a validation body, 500 otherwise. Then `title` and `type` are filled for statuses in the built-in table (409 gets "Conflict" and an RFC 9110 link; 422 gets "Unprocessable Entity" and an RFC 4918 link). - **`TypedResults.ValidationProblem` has no `statusCode` parameter**, and its `ValidationProblem` type reports a fixed 400; the source comment in `Results.ValidationProblem` notes that this is why the untyped helper wraps the body in a `ProblemHttpResult` instead. - Both write through `IProblemDetailsService` when it is registered, so `traceId` and `CustomizeProblemDetails` apply; without it they serialize the object directly as `application/problem+json`. ## Controller helpers In an MVC controller the methods live on `ControllerBase` and go through `ProblemDetailsFactory` (by default `DefaultProblemDetailsFactory`): 1. **`Problem(detail, instance, statusCode, title, type, extensions)`** creates a `ProblemDetails` with status 500 unless given, fills `title` and `type` from `ApiBehaviorOptions.ClientErrorMapping`, adds `traceId`, runs `CustomizeProblemDetails`, and returns an `ObjectResult`. 2. **`ValidationProblem()`** with no arguments uses the controller's `ModelState`; overloads accept another `ModelStateDictionary` or a ready `ValidationProblemDetails`. The status defaults to 400 and the result is a `BadRequestObjectResult`; any other status gives a plain `ObjectResult`. 3. MVC's output formatting adds `application/problem+json` and `application/problem+xml` as content types for any `ProblemDetails` value, so with XML formatters registered a client can ask for XML. ## A banking example A transfer endpoint rejects a request with two field errors: ```csharp app.MapPost("/api/transfers", (TransferRequest t) => { var errors = new Dictionary<string, string[]>(); if (t.Amount <= 0) errors["amount"] = ["Amount must be positive."]; if (t.FromIban == t.ToIban) errors["toIban"] = ["Choose a different account."]; return errors.Count > 0 ? Results.ValidationProblem(errors) : Results.Accepted(); }); ``` The client receives a 400 whose `errors` object holds `amount` and `toIban`, next to `type`, `title`, `status` and, with `AddProblemDetails()`, `traceId`. ## Look-alikes that are not validation problems - `Results.BadRequest(errors)` sends the dictionary as plain JSON with `application/json`: a 400, but no `type`, `title`, `status` or `errors` member. - `ControllerBase.BadRequest(ModelState)` wraps the model state in a `SerializableError`, a bare dictionary of field names to messages, again without the ProblemDetails members. - `Results.Json(new ProblemDetails { ... })` sends the right members with the wrong content type, `application/json`, and skips the default `type`, `title` and `traceId`. - A `ValidationProblemDetails` built by hand and returned through `Ok()` goes out as a 200, whatever its `Status` says, because the result's own status wins. Each of these looks fine in a quick manual test and breaks a client that branches on `Content-Type` or on the `errors` member. ## Choosing between them - A business failure with no field to point at (an account frozen, a limit exceeded): `Problem` with a fitting status and `detail`. - Field-level failures: `ValidationProblem`, so clients find the messages under one `errors` member. - In controllers, prefer the `ControllerBase` methods over constructing the classes yourself: they apply `ClientErrorMapping`, `traceId` and the customization callback, which a hand-built object returned through `Ok()` would skip.

  • How would you return an HttpValidationProblemDetails with status 422 from a Minimal API endpoint?
    Use `Results.ValidationProblem(errors, statusCode: 422)`. It builds the validation body with that status and returns it as a `ProblemHttpResult`, which also fills the 422 `title` and `type`. `TypedResults.ValidationProblem` cannot do it: it has no `statusCode` parameter and its result type always reports 400.
  • Why does ControllerBase.ValidationProblem() return a BadRequestObjectResult rather than a plain ObjectResult for 400?
    The source keeps producing `BadRequestObjectResult` for status 400 for compatibility with ASP.NET Core 2.x, so code and tests that check for that type keep working. Any other status, such as 422 passed through the `statusCode` parameter, comes back as an `ObjectResult` with that status.

  • Results.Problem() with no status code sends a 400 Bad Request.
  • TypedResults.ValidationProblem takes a statusCode parameter just like Results.ValidationProblem.
  • HttpValidationProblemDetails stores errors as one string per field, not an array of messages.
  • ControllerBase.ValidationProblem() needs ModelState passed in explicitly or it sends an empty errors object.
  • Returning Ok(new ProblemDetails { ... }) gives the same body as ControllerBase.Problem().