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)