在代码重复的许多操作中,基于模型状态验证属性时,我必须抛出自定义异常。
如何重构?
当前代码示例
[HttpGet("{jobId}/employeeLog")]
public async Task<IActionResult> GetFileLog(Guid jobId,
[FromQuery] Guid employeeId,
[SkipAndTopFromQuery] int? skip,
[SkipAndTopFromQuery] int? top,
[FromHeader(Name = "X-Correlation-ID")] string correlationId)
{
var employeeIdToValidate = ModelState["employeeId"];
var jobIdToValidate = ModelState["jobId"];
if (employeeIdToValidate == null || employeeIdToValidate != null && employeeIdToValidate.Errors.Any())
throw new InvalidFileIdException();
if (jobIdToValidate == null || jobIdToValidate != null && jobIdToValidate.Errors.Any())
throw new InvalidApplicationIdException();
if (!ModelState.IsValid)
return StatusCode((int)HttpStatusCode.BadRequest);
....
}
答案 0 :(得分:1)
如果您想简化 if 语句,可以使用Null Propagation Operator in C#
public async Task<IActionResult> GetFileLog(Guid jobId,
[FromQuery] Guid employeeId,
[SkipAndTopFromQuery] int? skip,
[SkipAndTopFromQuery] int? top,
[FromHeader(Name = "X-Correlation-ID")] string correlationId)
{
var employeeIdToValidate = ModelState["employeeId"];
var jobIdToValidate = ModelState["jobId"];
if (employeeIdToValidate?.Errors?.Any() ?? true)
throw new InvalidFileIdException();
if (jobIdToValidate?.Errors?.Any() ?? true)
throw new InvalidApplicationIdException();
if (!ModelState.IsValid)
return StatusCode((int)HttpStatusCode.BadRequest);
....
}
此外,如果您的ModelState返回相同的对象或具有公共接口的对象,您可以将检查移动到某种方法。
顺便说一句,您可以通过创建某种类(如 validator )来从您的方法中拆分验证:
class GetFileLogValidatior: ValidatorBase {
public override void Validate(GetFileLogValidatiorContext context) {
var employeeIdToValidate = context.EmployeeIdToValidate;
var jobIdToValidate = context.JobIdToValidate;
if (employeeIdToValidate?.Errors?.Any() ?? true)
throw new InvalidFileIdException();
if (jobIdToValidate?.Errors?.Any() ?? true)
throw new InvalidApplicationIdException();
}
}