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)