Model binding converts data from an HTTP request into .NET parameters and objects. Model validation then checks that those values meet your rules before the action runs. Model binding sources - Route values: /api/orders/{id} → int id - Query string: ?page=2&status=Paid - Request body: JSON deserialised with System.Text.Json (one body parameter per action) - Headers: [FromHeader(Name = "X-Correlation-ID")] - Form data and files: [FromForm], IFormFile - Services from dependency injection: [FromServices] (inferred automatically in recent versions) Explicit attributes: [FromRoute], [FromQuery], [FromBody], [FromHeader], [FromForm], [FromServices]. With [ApiController], ASP.NET Core infers sources: complex types come from the body, simple types from route or query, IFormFile from the form, and registered services from DI. Example [ApiController] [Route("api/orders")] public class OrdersController(IOrderService orders) : ControllerBase { [HttpPost] public async Task<ActionResult<OrderDto>> Create([FromBody] CreateOrderRequest request, CancellationToken ct) { var order = await orders.CreateAsync(request, ct); return CreatedAtAction(nameof(Get), new { id = order.Id }, order); } [HttpGet("{id:int}")] public Task<OrderDto?> Get(int id, [FromQuery] bool includeItems = false) => orders.GetAsync(id, includeItems); } Validation with data annotations public sealed class CreateOrderRequest { [Required] public string CustomerId { get; set; } = ""; [Required, MinLength(1)] public List<OrderLineRequest> Lines { get; set; } = []; [StringLength(500)] public string? Notes { get; set; } } public sealed class OrderLineRequest { [Range(1, int.MaxValue)] public int ProductId { get; set; } [Range(1, 100)] public int Quantity { get; set; } } Other attributes: [EmailAddress], [Phone], [RegularExpression], [Compare], [Url], [MaxLength]. Custom attributes inherit from ValidationAttribute; class-level rules can implement IValidatableObject. How validation results are handled - Binding and validation errors are collected in ModelState. - With [ApiController], if ModelState is invalid, ASP.NET Core automatically returns 400 Bad Request with a ValidationProblemDetails body (RFC 7807/9457) listing errors per field — the action does not run. - Without [ApiController], check if (!ModelState.IsValid) return ValidationProblem(ModelState); manually. - Nested objects and collections are validated recursively. Example error response { "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1", "title": "One or more validation errors occurred.", "status": 400, "errors": { "Lines[0].Quantity": ["The field Quantity must be between 1 and 100."] } } Minimal APIs - Parameters bind automatically from route, query, headers, body and services. - .NET 10 added built-in validation for minimal APIs (builder.Services.AddValidation()) using the same data annotations. In earlier versions, use endpoint filters or libraries. FluentValidation - A popular alternative for complex rules, keeping validation separate from DTOs: public sealed class CreateOrderValidator : AbstractValidator<CreateOrderRequest> { public CreateOrderValidator() { RuleFor(x => x.CustomerId).NotEmpty(); RuleForEach(x => x.Lines).ChildRules(l => l.RuleFor(x => x.Quantity).InclusiveBetween(1, 100)); } } Best practices - Use dedicated request DTOs (not entities) to avoid over-posting. - Validate business rules that need the database (stock, uniqueness) in the service layer and return 409 or 422 as appropriate. - Never trust client-side validation alone. - Limit request sizes and collection lengths. Interview summary: "Model binding maps route, query, header, form and body data to action parameters. Validation runs data annotation or custom rules, storing errors in ModelState; with [ApiController], invalid models automatically return 400 with Validation Problem Details."
Ravindra Wadile · · 0 likes