Skip to content
Tutorials Center
My learning

Topics

Lesson 138 of 182 ยท ASP.NET Core

Validation and Problem Details

Validate input in C# web APIs with DataAnnotations, IValidatableObject and endpoint filters, and return consistent errors with ProblemDetails, ValidationProblem and IExceptionHandler.

Every web API receives input it cannot trust. A name arrives empty, an age is negative, a date is in the wrong format, a JSON body is missing half its fields. If you do nothing, the bad data travels deep into your code and fails somewhere far from the cause, or worse, it is stored and fails later. Validation is the habit of checking input at the boundary and answering clearly: "this request is not acceptable, and here is why".

The second half of the job is the answer itself. Clients, whether a browser app or another service, need errors in a predictable shape. The web has a standard for that: Problem Details, defined in RFC 9457 (which replaced RFC 7807) and built into ASP.NET Core. In this lesson you will validate objects with DataAnnotations, write your own rules, plug validation into minimal APIs with endpoint filters, and return errors as application/problem+json, including for exceptions and for plain 404s.

Each example starts a Kestrel server on loopback and calls it with HttpClient, as in the previous lessons. The using lines are what a web project adds implicitly; our single-file runner needs them spelled out. Fields that differ per request (such as the trace id in a problem response) are not printed, so the output is stable.

Validating an object with DataAnnotations

The namespace System.ComponentModel.DataAnnotations contains attributes that describe rules on properties: [Required], [StringLength], [MinLength], [Range], [EmailAddress], [RegularExpression] and more. They only describe the rule. Something else has to run the check. The simplest runner is the static Validator class, and it works in any program, not just web apps, so we can explore it first without a server:

C# Validator.TryValidateObject

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Look at what happens for the empty object: Age is 0, outside the range, so it fails; Name and Email are empty strings, and [Required] rejects empty strings by default. The default messages are built from the property name ("The Name field is required."), and you can override them with ErrorMessage.

validateAllProperties: true is easy to forget. With the default false, Validator.TryValidateObject only checks [Required] properties and ignores [Range], [StringLength] and the rest. Many hand-rolled validation helpers have been silently weaker than intended because of that one flag.

Two more facts about annotations are worth knowing early:

  • null passes most rules. [Range], [StringLength], [EmailAddress] and friends treat null as "nothing to check". Combine them with [Required] when the value must exist. With nullable reference types enabled, a non-nullable string property that is missing from the JSON body is still null at runtime, because the compiler cannot control deserialization. That is why [Required] and the C# required keyword (see constructors) both appear in API models.
  • Annotations check shape, not business truth. "The email is well-formed" is validation. "This email is not already registered" needs a database lookup and belongs in your service layer, usually answered with a 409 Conflict.

Custom rules: attributes and IValidatableObject

When the built-in attributes are not enough you have two options. A custom attribute is reusable across many properties:

C#
public sealed class NotPastDateAttribute : ValidationAttribute
{
    protected override ValidationResult? IsValid(object? value, ValidationContext context)
    {
        if (value is DateOnly date && date < DateOnly.FromDateTime(DateTime.UtcNow))
        {
            return new ValidationResult("The date must not be in the past.", [context.MemberName!]);
        }
        return ValidationResult.Success;
    }
}

When a rule involves several properties at once (a start date before an end date, a password that must not contain the user name), implement IValidatableObject. Its Validate method runs after the attribute checks pass and can report errors against any members:

C# Cross-property rules with IValidatableObject

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first booking passes. The second fails the Guests attribute, and notice that the date rule is not reported for it even though check-out equals check-in: IValidatableObject.Validate only runs when all attribute checks succeed. That is a feature (no confusing cascades) and a gotcha (users see errors one batch at a time). The third booking has an attribute error (Guest), so its date rule is also skipped until the name is fixed. If you want every message at once, put all rules in Validate instead of splitting them between attributes and the method.

Validation in a minimal API

Controllers with [ApiController] validate automatically and answer 400 with a problem body. Minimal APIs historically did not: a handler receives the bound object and it is your job to check it. .NET 10 added opt-in built-in validation for minimal APIs: you call builder.Services.AddValidation() and DataAnnotations on your parameter types are checked before the handler runs. It relies on a compile-time source generator, which web projects pick up through the SDK:

C#
// Read-only: .NET 10 built-in validation in a normal web project
builder.Services.AddValidation();

app.MapPost("/users", (NewUser user) => TypedResults.Created($"/users/{user.Name}", user));
// A request that breaks the rules gets a 400 ValidationProblem response
// before the handler is called.

Our single-file runner does not run that generator (a request with an empty name still reached the handler when we tried it), so we will use the approach that works in every .NET version and teaches the mechanics: an endpoint filter. A generic filter finds the argument of type T, validates it, and short-circuits with Results.ValidationProblem when it is invalid.

C# A reusable validation filter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The valid request goes through and returns 201 Created with the user. The invalid one stops in the filter: the status is 400, the media type is application/problem+json, and the errors object maps each property name to its messages. Frontend code can attach those messages to the matching form fields without parsing text. The filter is a single class used with any model type, so adding validation to another endpoint is one line.

Problem Details: one shape for every error

A problem details object is a JSON document with a handful of standard members:

Member Meaning
type A URI that identifies the kind of problem (documentation for clients; may be relative or a URL under your control).
title A short, human-readable summary that does not change between occurrences.
status The HTTP status code, repeated in the body for convenience.
detail An explanation specific to this occurrence.
instance A URI identifying this particular occurrence (for example the request path).

You may add your own extension members, such as errors for validation or traceId for support teams. ASP.NET Core represents the document with the class ProblemDetails (and ValidationProblemDetails, which adds the errors dictionary). The helpers Results.Problem(...) and TypedResults.Problem(...) build one for a minimal API handler.

C# Returning problems from handlers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first call succeeds with plain JSON. The other two return application/problem+json. Clients can switch on status or on type, and the human-friendly parts (title, detail) can change without breaking them. Prefer type as the machine-readable identifier; never ask clients to parse detail.

Pick the status that best describes the failure: 400 for malformed or invalid input, 401/403 for authentication and permission problems, 404 when the resource does not exist, 409 for a conflict with current state (duplicate email), and 422 when the request is well-formed but semantically unacceptable. Teams differ on 400 versus 422 for validation; choose one and use it everywhere.

Making every error a problem

Errors do not only come from your handlers. A route that matches nothing returns an empty 404, and an unhandled exception returns an empty 500 (or a developer page). To make all of them use the same format, register the problem details service and two pieces of middleware:

  • builder.Services.AddProblemDetails() turns on the IProblemDetailsService. Its default output includes a traceId, and you can add data to every problem with CustomizeProblemDetails.
  • app.UseStatusCodePages() fills in an empty body for status codes such as 404 and 405 (it uses the problem details service when it is registered).
  • app.UseExceptionHandler() catches unhandled exceptions and, with problem details registered, writes a 500 problem.

For exceptions you want to translate (a KeyNotFoundException into 404, your own DomainException into 422), implement IExceptionHandler. It returns true when it handled the exception, so a chain of handlers can each take their own cases. This is the structured version of the exception middleware from the previous lesson.

C# IExceptionHandler and AddProblemDetails

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Compare the two failures. OutOfStockException was recognized and became a 409 with a helpful detail. The unexpected InvalidOperationException (whose message contained a "password") became a generic 500 problem whose body says nothing about the cause: the handler did not claim it, so the default UseExceptionHandler behavior applied. Unknown routes also became problems, thanks to UseStatusCodePages. And every problem carries the app extension we added in CustomizeProblemDetails.

Note the primary-constructor classes (OutOfStockException(string sku), DomainExceptionHandler(IProblemDetailsService ...)): they keep small handler classes short. See primary constructors.

Never put exception messages, stack traces or SQL in a problem detail for unexpected errors. Log them with the trace id (see Logging) and give the client only the id. Developers can then look the failure up on the server without the client seeing internals.

Validation design tips

  • Validate at the edge, enforce in the domain. Annotations on request DTOs stop garbage early; your domain objects should still protect their own invariants (see validation and contracts), because they are also created from queues, files and tests.
  • Use separate request models. A NewUser DTO with validation attributes is a different thing from a User entity. This also prevents over-posting, where a client sets fields (like IsAdmin) that you never meant to expose.
  • Return all the errors you can. One round trip with five messages beats five round trips with one message each.
  • Keep messages user-safe and stable. They end up on screens, in logs and in client code.
  • Do not validate with exceptions on the hot path. Failing validation is normal; throwing for it is slow and noisy. Return a result and map it to a response.
  • Serialization errors are also validation. A malformed JSON body or a string where a number is expected is rejected by the binder before your code runs; with problem details enabled it also arrives as a 400 problem.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Validator.TryValidateObject(obj, context, results) check when validateAllProperties is left at its default of false?

    With validateAllProperties false, only [Required] attributes are checked. Pass true to check Range, StringLength, EmailAddress and the rest.
  2. 2. When does IValidatableObject.Validate run during Validator.TryValidateObject?

    The object-level Validate method is called only when the attribute checks pass, so cross-property errors may appear in a second round.
  3. 3. Which media type does a problem details response use?

    RFC 9457 defines application/problem+json (and application/problem+xml). ASP.NET Core writes the JSON form.
  4. 4. What is the purpose of an IExceptionHandler?

    Handlers registered with AddExceptionHandler are asked in order. Each returns true if it wrote a response, or false to let the next handler or the default behavior run.
  5. 5. Which member of a problem details document should clients use to recognize the kind of error reliably?

    Titles and details are for humans and can be reworded. The type URI and the status code are the stable, machine-readable parts.

Summary

  • Validate input at the boundary and answer with a precise 400 (or 422) instead of letting bad data travel inward.
  • DataAnnotations describe rules; Validator.TryValidateObject(..., validateAllProperties: true) runs them anywhere; [Required] is needed because most rules ignore null.
  • Use custom ValidationAttribute classes for reusable rules and IValidatableObject for rules across properties; remember it runs only after the attributes pass.
  • In minimal APIs, validate with an endpoint filter (or AddValidation() in .NET 10 web projects) and return Results.ValidationProblem.
  • Problem Details (RFC 9457, application/problem+json) gives every error the same shape: type, title, status, detail, instance plus extensions.
  • AddProblemDetails, UseStatusCodePages, UseExceptionHandler and IExceptionHandler make validation errors, 404s and exceptions consistent, without leaking internals.

Next: Authentication and Authorization