Validation in Minimal APIs has improved a lot! Here's how it changed over time:
🔹 .𝗡𝗘𝗧 𝟲 & 𝟳
– No built-in validation support
– You had to write custom code manually like:
var context = new ValidationContext(model);
Validator.TryValidateObject(model, context, results, true);
🔹 .𝗡𝗘𝗧 𝟴
– Built-in validation support introduced
– Simply add validation service:
builder.Services.AddValidation();
– Use [Validate] attribute in Minimal API:
app.MapPost("/register", ([Validate] UserModel user) =>
Results.Ok("Valid user"));
– Invalid data? You automatically get a 400 Bad Request with error details
🔹 .𝗡𝗘𝗧 𝟭𝟬 – 𝗠𝗼𝗿𝗲 𝗣𝗼𝘄𝗲𝗿𝗳𝘂𝗹
– Now validates:
- Query parameters
- Headers
- Request body
– You can use 𝗿𝗲𝗰𝗼𝗿𝗱 𝘁𝘆𝗽𝗲𝘀 with validation attributes:
public record Product(
[Required] string Name,
[Range(1, 1000)] int Quantity);
– Mapping:
app.MapPost("/products", (Product product) =>
TypedResults.Ok(product));
– Want to 𝗱𝗶𝘀𝗮𝗯𝗹𝗲 𝘃𝗮𝗹𝗶𝗱𝗮𝘁𝗶𝗼𝗻 for a specific endpoint?
app.MapPost("/products",
([EvenNumber(ErrorMessage = "Product ID must be even")] int productId, [Required] string name) =>
TypedResults.Ok(productId))
.DisableValidation();
𝗛𝗼𝘄 𝗮𝗿𝗲 𝘆𝗼𝘂 𝗵𝗮𝗻𝗱𝗹𝗶𝗻𝗴 𝘃𝗮𝗹𝗶𝗱𝗮𝘁𝗶𝗼𝗻 𝗶𝗻 𝘆𝗼𝘂𝗿 𝗔𝗣𝗜𝘀 𝘁𝗼𝗱𝗮𝘆?
𝗛𝗮𝘃𝗲 𝘆𝗼𝘂 𝘁𝗿𝗶𝗲𝗱 𝘁𝗵𝗲 𝗻𝗲𝘄 [𝗩𝗮𝗹𝗶𝗱𝗮𝘁𝗲] 𝗮𝘁𝘁𝗿𝗶𝗯𝘂𝘁𝗲 𝗶𝗻 .𝗡𝗘𝗧 𝟴 𝗼𝗿 .𝗡𝗘𝗧 𝟭𝟬?
Top comments (0)