dotnet minimal api extension method for logic validation

Hey guys I have three if statements that are repeated too often in many endpoints, how can I make an extension method to use on my endpoints? here is the current code
c#
app.MapPost(
"create-income-register",
[Authorize]
async (
CancellationToken token,
[FromBody]
CreateIncomeRegisterRequest request,
[FromServices]
IRegisterService registerService
) =>
{
if (!RegisterType.CheckIfIsValidType(request.Type, out bool isTransfer))
{
throw new InvalidRegisterTypeException();
}

if(!RegisterRepetitionType.CheckIfIsValidType(request.RepetitionType))
{
throw new InvalidRegisterRepetitionTypeException();
}

if(!Periodicities.CheckIfIsValidType(request.Periodicity))
{
throw new InvalidPeriodicityException();
}

await registerService.CreateIncomeRegister(request, token);
return Results.Ok();
}
);
c#
app.MapPost(
"create-income-register",
[Authorize]
async (
CancellationToken token,
[FromBody]
CreateIncomeRegisterRequest request,
[FromServices]
IRegisterService registerService
) =>
{
if (!RegisterType.CheckIfIsValidType(request.Type, out bool isTransfer))
{
throw new InvalidRegisterTypeException();
}

if(!RegisterRepetitionType.CheckIfIsValidType(request.RepetitionType))
{
throw new InvalidRegisterRepetitionTypeException();
}

if(!Periodicities.CheckIfIsValidType(request.Periodicity))
{
throw new InvalidPeriodicityException();
}

await registerService.CreateIncomeRegister(request, token);
return Results.Ok();
}
);
and I want it to be something like:
c#
app.MapPost(
"create-income-register",
[Authorize]
async (
CancellationToken token,
[FromBody]
CreateIncomeRegisterRequest request,
[FromServices]
IRegisterService registerService
) =>
{
await registerService.CreateIncomeRegister(request, token);
return Results.Ok();
}
).WithRegisterValidation();
c#
app.MapPost(
"create-income-register",
[Authorize]
async (
CancellationToken token,
[FromBody]
CreateIncomeRegisterRequest request,
[FromServices]
IRegisterService registerService
) =>
{
await registerService.CreateIncomeRegister(request, token);
return Results.Ok();
}
).WithRegisterValidation();
Thanks!
3 Replies
Angius
Angius3w ago
Use a middleware or a filter? Make an IEndpointFilter and use it on the endpoints that need it with .AddEndpointFilter<T>()
Sossenbinder
Sossenbinder3w ago
+1 for filters, seems like the best option here

Did you find this page helpful?