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
and I want it to be something like:
Thanks!
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!
message.txt4.26KB
message.txt4.26KB