DEV Community

Supraja Tangella
Supraja Tangella

Posted on

๐—–๐—น๐—ฒ๐—ฎ๐—ป ๐—–๐—ผ๐—ฑ๐—ฒ ๐˜„๐—ถ๐˜๐—ต ๐—”๐—ฑ๐—ฑ๐—˜๐—ป๐—ฑ๐—ฝ๐—ผ๐—ถ๐—ป๐˜๐—™๐—ถ๐—น๐˜๐—ฒ๐—ฟ ๐—ถ๐—ป ๐— ๐—ถ๐—ป๐—ถ๐—บ๐—ฎ๐—น ๐—”๐—ฃ๐—œ๐˜€

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)