In Minimal APIs, it's common to validate input manually inside each handler. But there's a better way.
Using .AddEndpointFilter() gives you a cleaner, reusable approach to validation. Here's why it's better:
๐๐ฒ๐ป๐ฒ๐ณ๐ถ๐๐ ๐ผ๐ณ ๐๐๐ถ๐ป๐ด ๐๐ฑ๐ฑ๐๐ป๐ฑ๐ฝ๐ผ๐ถ๐ป๐๐๐ถ๐น๐๐ฒ๐ฟ():
๐๐น๐ฒ๐ฎ๐ป๐ฒ๐ฟ ๐๐ฎ๐ป๐ฑ๐น๐ฒ๐ฟ๐: Keeps your endpoint logic focused on the core task.
// Without cluttering the method:
group.MapPost("/", CreateTodo).AddEndpointFilter(ValidateTodo);
๐ฅ๐ฒ๐๐๐ฎ๐ฏ๐ถ๐น๐ถ๐๐: Apply the same logic to multiple endpoints.
builder.Services.AddScoped();
๐๐ฒ๐ป๐๐ฟ๐ฎ๐น๐ถ๐๐ฒ๐ฑ ๐ฉ๐ฎ๐น๐ถ๐ฑ๐ฎ๐๐ถ๐ผ๐ป: Easier to manage and update validation logic.
๐ฆ๐ต๐ผ๐ฟ๐-๐ฐ๐ถ๐ฟ๐ฐ๐๐ถ๐๐ ๐ผ๐ป ๐๐ฟ๐ฟ๐ผ๐ฟ: Automatically returns errors before hitting the handler.
๐๐ผ๐น๐น๐ผ๐๐ ๐ ๐ถ๐ฑ๐ฑ๐น๐ฒ๐๐ฎ๐ฟ๐ฒ ๐ฃ๐ฎ๐๐๐ฒ๐ฟ๐ป: Keeps the pipeline extensible and testable.
๐๐ผ๐ ๐ฎ๐ฟ๐ฒ ๐๐ผ๐ ๐ต๐ฎ๐ป๐ฑ๐น๐ถ๐ป๐ด ๐ถ๐ป๐ฝ๐๐ ๐๐ฎ๐น๐ถ๐ฑ๐ฎ๐๐ถ๐ผ๐ป ๐ถ๐ป ๐๐ผ๐๐ฟ ๐ ๐ถ๐ป๐ถ๐บ๐ฎ๐น ๐๐ฃ๐๐โ๐ถ๐ป๐๐ถ๐ฑ๐ฒ ๐ต๐ฎ๐ป๐ฑ๐น๐ฒ๐ฟ๐ ๐ผ๐ฟ ๐๐๐ถ๐ป๐ด ๐ฒ๐ป๐ฑ๐ฝ๐ผ๐ถ๐ป๐ ๐ณ๐ถ๐น๐๐ฒ๐ฟ๐?
Top comments (0)