【发布时间】:2023-03-23 03:16:02
【问题描述】:
我在我的 Web 应用程序中使用 net core 3.1。我陷入了想有条件地验证模型的情况。以下是我的模型:
学生模型:
public class StudentModel
{
public int StudenId {get; set;}
public string StudenName {get; set;}
public bool HasSiblings {get; set;}
public List<SiblingModel> SiblingDetails {get; set;}
}
兄弟模型
public class SiblinModel
{
public int SiblingId {get; set;}
[Required]
public string SiblingName {get; set;}
}
现在,我只想在 StudentModel 中的 HasSibling 设置为 true 时验证 SiblingModel。
注意:我不想使用 IValidatableObject 然后验证 SiblingModel 的每个属性。我仅以上述模型为例。在实际模型中,我验证了大约 10-12 个字段。因此,为每个属性编写验证检查将是一项乏味的任务。
有没有一种方法可以有条件地验证整个模型,即如果 HasSibling 设置为 true,则仅验证同级模型。
另外,我在我的项目中使用操作过滤器来自动检查每个请求中的验证。
public class ValidationFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
ApiResponseModel<IEnumerable<ValidationErrorModel>> apiResponseModel = new ApiResponseModel<IEnumerable<ValidationErrorModel>>();
apiResponseModel.ResponseCode = (int)HttpStatusCode.BadRequest;
apiResponseModel.ResponseMessage = string.Join(" ",
context.ModelState.Values.Where(E => E.Errors.Count > 0)
.SelectMany(E => E.Errors)
.Select(E => E.ErrorMessage)
.ToArray());
apiResponseModel.ResponseData = null;
context.Result = new OkObjectResult(apiResponseModel);
}
}
}
那么有什么办法,或者我必须使用 IValidatableObject 手动编写验证检查。
【问题讨论】:
标签: c# asp.net-web-api asp.net-core-webapi