SkillPilotAI

Model binding and validation

Model binding converts request data (route, query, headers, body) into C# parameters; validation checks the rules on those values. With [ApiController], an invalid ModelState automatically returns 400 ValidationProblemDetails before the action runs.

46.1 Why is it used?

  • Without validation, an empty name and a price of -50 are saved and returned as 201 Created.
  • Binding only converts: in JSON "" and -50 are valid values, so rules must be stated separately.
  • One consistent 400 format lists a problem per field, so frontends can show errors next to inputs.
  • Server-side validation is mandatory: anyone can call the API directly with curl.

46.2 The bug: any data gets through

The Create action from the previous video (CreateProductRequest added straight to the store):

Output
$ curl -i localhost:5046/api/products \  -H "Content-Type: application/json" \  -d '{"name":"","price":-50}'HTTP/1.1 201 CreatedContent-Type: application/json; charset=utf-8Location: http://localhost:5046/api/products/3{ "id": 3, "name": "", "price": -50 }
How bad data got through
  1. 1.Binding: JSON -> CreateProductRequest

  2. 2."" and -50 are valid JSON values

  3. 3.No rules: nothing is checked

  4. 4.Action saves bad data -> 201 Created

Binding = convert, validation = check

46.3 Binding sources

AttributeSourceExample
[FromRoute]URL path/api/products/{id}
[FromQuery]Query string?q=mixer
[FromBody]JSON bodyCreateProductRequest
[FromHeader]Request headersX-Api-Key
[FromForm]HTML form, file uploadsIFormFile
[FromServices]DI containerIValidator<T>

46.4 FromQuery: a search endpoint

C#
[HttpGet("search")]public IEnumerable<ProductDto> Search(    [FromQuery] string q,    [FromQuery] decimal? maxPrice){    return store.All()        .Where(p => p.Name.Contains(q,            StringComparison.OrdinalIgnoreCase))        .Where(p => maxPrice is null            || p.Price <= maxPrice)        .Select(p => p.ToDto());}
Output
$ curl -i -G localhost:5046/api/products/search \  -d q=mixer -d maxPrice=3000HTTP/1.1 200 OKContent-Type: application/json; charset=utf-8[ { "id": 1, "name": "Mixer Grinder", "price": 2499 } ] $ curl -i -G localhost:5046/api/products/search \  -d maxPrice=500HTTP/1.1 400 Bad RequestContent-Type: application/problem+json; charset=utf-8{  "title": "One or more validation errors occurred.",  "status": 400,  "errors": { "q": ["The q field is required."] }}
  • With [ApiController] these attributes are optional: simple types bind from route/query, complex types from the body.
  • q is a non-nullable string, so it is treated as required: leaving it out gives an automatic 400.
  • maxPrice is decimal?, so it is optional.

46.5 Fix: DataAnnotations

C#
using System.ComponentModel.DataAnnotations; public record CreateProductRequest(    [Required, MinLength(3), MaxLength(60)]    string Name,    [Range(1, 500000)]    decimal Price);
Output
$ curl -i localhost:5046/api/products \  -H "Content-Type: application/json" \  -d '{"name":"","price":-50}'HTTP/1.1 400 Bad RequestContent-Type: application/problem+json; charset=utf-8{  "title": "One or more validation errors occurred.",  "status": 400,  "errors": {    "Name": ["The Name field is required.", ...],    "Price": ["The field Price must be between 1 and 500000."]  }}
  • Rules are attributes on the request record: Required, MinLength(3), MaxLength(60), Range(1, 500000).
  • Not one line of the controller changed; the same request now gives 400 with a separate problem per field.
The flow of an automatic 400
  1. 1.Model binding: request -> parameters (conversion errors -> ModelState)

  2. 2.Validation attributes are checked (errors -> ModelState)

  3. 3.[ApiController] checks ModelState before the action

  4. 4.Invalid: action skipped, 400 ValidationProblemDetails returned

Invalid ModelState = the action never runs

46.6 Checkpoint: maxPrice=abc?

Output
$ curl -i -G localhost:5046/api/products/search \  -d q=bottle -d maxPrice=abcHTTP/1.1 400 Bad RequestContent-Type: application/problem+json; charset=utf-8{  "title": "One or more validation errors occurred.",  "status": 400,  "errors": { "maxPrice": ["The value 'abc' is not valid."] }}
  • abc cannot be converted to decimal, so binding puts the error into ModelState.
  • The action never runs (maxPrice is not silently null); errors show "The value 'abc' is not valid."

46.7 ModelState: adding your own error

C#
[HttpPost]public ActionResult<ProductDto> Create(    [FromBody] CreateProductRequest request){    if (store.NameExists(request.Name))    {        ModelState.AddModelError("Name",            "This name already exists.");        return ValidationProblem(ModelState);    }    var product = store.Add(        request.Name, request.Price);    return CreatedAtAction(nameof(GetById),        new { id = product.Id }, product.ToDto());}
Output
$ curl -i localhost:5046/api/products \  -H "Content-Type: application/json" \  -d '{"name":"steel bottle","price":450}'HTTP/1.1 400 Bad RequestContent-Type: application/problem+json; charset=utf-8{  "title": "One or more validation errors occurred.",  "status": 400,  "errors": { "Name": ["This name already exists."] }}
  • Rules that need the store (name already exists) cannot be attributes.
  • ModelState.AddModelError("Name", ...) adds the error; ValidationProblem(ModelState) returns it in the same format as the automatic 400.

46.8 IValidatableObject: a cross-field rule

C#
public record CreateProductRequest(    [Required, MinLength(3), MaxLength(60)]    string Name,    [Range(1, 500000)] decimal Price,    decimal? SalePrice) : IValidatableObject{    public IEnumerable<ValidationResult> Validate(        ValidationContext context)    {        if (SalePrice >= Price)            yield return new ValidationResult(                "SalePrice must be below Price.",                [nameof(SalePrice)]);    }}
Output
$ curl -i localhost:5046/api/products \  -H "Content-Type: application/json" \  -d '{"name":"Tawa","price":699,"salePrice":799}'HTTP/1.1 400 Bad RequestContent-Type: application/problem+json; charset=utf-8{  "title": "One or more validation errors occurred.",  "status": 400,  "errors": {    "SalePrice": ["SalePrice must be below Price."]  }} $ curl -i localhost:5046/api/products \  -H "Content-Type: application/json" \  -d '{"name":"Tawa","price":-5,"salePrice":799}'HTTP/1.1 400 Bad RequestContent-Type: application/problem+json; charset=utf-8{  "status": 400,  "errors": {    "Price": ["The field Price must be between 1 and 500000."]  }}
  • Validate returns a ValidationResult with a message and the field name for every bad case.
  • Validate runs only when all attributes pass: with price -5 you only see the Price range error.

46.9 FluentValidation: rules in their own class

C#
using FluentValidation;public class CreateProductValidator    : AbstractValidator<CreateProductRequest>{    public CreateProductValidator()    {        RuleFor(x => x.Name)            .NotEmpty().Length(3, 60);        RuleFor(x => x.Price)            .InclusiveBetween(1, 500000);        RuleFor(x => x.SalePrice)            .LessThan(x => x.Price)            .When(x => x.SalePrice is not null);    }}
Output
$ dotnet add package FluentValidation.DependencyInjectionExtensionsinfo : PackageReference for package  'FluentValidation.DependencyInjectionExtensions'  version '12.2.0' added to file 'Shop.csproj'. # Program.csbuilder.Services.AddValidatorsFromAssembly(    typeof(Program).Assembly);
C#
[HttpPost]public async Task<ActionResult<ProductDto>> Create(    CreateProductRequest request,    IValidator<CreateProductRequest> validator){    var check =        await validator.ValidateAsync(request);    foreach (var e in check.Errors)        ModelState.AddModelError(            e.PropertyName, e.ErrorMessage);    if (!ModelState.IsValid)        return ValidationProblem(ModelState);     return SaveAndCreated(request);}
Output
$ curl -i localhost:5046/api/products \  -H "Content-Type: application/json" \  -d '{"name":"","price":-50}'HTTP/1.1 400 Bad RequestContent-Type: application/problem+json; charset=utf-8{  "title": "One or more validation errors occurred.",  "status": 400,  "errors": {    "Name": ["'Name' must not be empty.", ...],    "Price": ["'Price' must be between 1 and 500000.      You entered -50."]  }}
  • AbstractValidator<T> with RuleFor chains keeps rules away from the models.
  • When(...) checks SalePrice only when a value is sent.
  • AddValidatorsFromAssembly registers all validators in DI; IValidator<T> is injected into the action.
  • Errors are copied into ModelState so the response keeps the same ValidationProblem format. The old automatic integration is no longer recommended.

46.10 Comparison: validation options

OptionBest forExample
DataAnnotationsSimple per-field rules[Required], [Range(1, 500000)]
IValidatableObjectCross-field rules inside the modelSalePrice < Price
ModelState.AddModelErrorRules that need the database/storeName already exists
FluentValidationLarge rule sets in separate classesRuleFor(x => x.Name).NotEmpty()

46.11 Common mistakes

  • [Required] on a value type (decimal): it is never null, a missing price becomes 0 and passes. Use Range, or make it nullable + Required.
  • Writing if (!ModelState.IsValid) in every action: [ApiController] already does it; check manually only when you add errors yourself.
  • Relying on frontend validation only.
C#
// Wrong: Required on a value type does nothingpublic record CreateProductRequest(    [Required] string Name,    [Required] decimal Price);// POST {"name":"Tawa"} -> 201 Created// {"id":3,"name":"Tawa","price":0} // Right: Range starts at 1, so 0 is rejected toopublic record CreateProductRequest(    [Required] string Name,    [Range(1, 500000)] decimal Price);// POST {"name":"Tawa"} -> 400 Bad Request// Price: must be between 1 and 500000

46.12 Validation rules

  1. A separate DTO record per request, with the rules on it.
  2. DataAnnotations for field rules, IValidatableObject for cross-field rules.
  3. Value types: Range or a nullable type, not Required.
  4. Database checks: AddModelError + ValidationProblem.
  5. Many rules: move them to FluentValidation validators.

46.13 Interview tips

  • Model binding fills parameters from route, query, headers and body; conversion errors go into ModelState.
  • DataAnnotations for fields, IValidatableObject for cross-field rules.
  • [ApiController] automatically returns 400 ValidationProblemDetails for an invalid ModelState; the action never runs.
  • FluentValidation for complex rules, and validation always happens on the server.