DEV Community

Supraja Tangella
Supraja Tangella

Posted on

๐—›๐—ฎ๐—ป๐—ฑ๐—น๐—ถ๐—ป๐—ด ๐—ฉ๐—ฎ๐—น๐—ถ๐—ฑ๐—ฎ๐˜๐—ถ๐—ผ๐—ป๐˜€ ๐—ถ๐—ป ๐— ๐—ถ๐—ป๐—ถ๐—บ๐—ฎ๐—น ๐—”๐—ฃ๐—œ โ€“ ๐—ช๐—ต๐—ฎ๐˜โ€™๐˜€ ๐—ก๐—ฒ๐˜„ ๐—ณ๐—ฟ๐—ผ๐—บ .๐—ก๐—˜๐—ง ๐Ÿฒ ๐˜๐—ผ .๐—ก๐—˜๐—ง ๐Ÿญ๐Ÿฌ

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)