假设我有一个具有以下方法的控制器类
public async Task<XYZ> ProcessSomeAPICall(User u, int a, string b, bool c) {
if (u.Name == "Bubba" && a < 10) {
throw new BubbaException("there is no way Bubba can do more then 10")
}
if (u.Position == null && !c) {
throw new EmploymentException("user without a job should have c set up")
}
//... more input parameter checks here
return await executeSomeApplicationLogic(u, a, b, c);
}
是否有任何框架可以帮助我最大限度地减少执行参数检查所需的条件代码量?
您可以使用 FluentValidation 来验证您的输入并提高可读性。
public class UsersController : ControllerBase
{
public async Task<XYZ> ProcessSomeAPICall(RegisterUserCommand command) // command => user in your sample
{
command.Validate();
}
}
public class RegisterUserCommand
public string UserName { get; set; }
// some properties
public void Validate()
{
new RegisterUserCommandValidator().Validate(this).RaiseExceptionIfNeed();
}
}
public class RegisterUserCommandValidator : AbstractValidator
{
public RegisterUserCommandValidator()
{
RuleFor(p=> p.UserName).NotEmpty().NotNull().WithMessage("some-message");
}
}