[英]How to conditionally validate entire model in ASP.NET Core Web API?
I am using net core 3.1 in my Web-Application.我在我的 Web 应用程序中使用 net core 3.1。 I am stuck in a situation where I want to validate a model conditionally.
我陷入了我想有条件地验证 model 的情况。 Below is my models:
下面是我的模型:
Studen tModel:学生模型:
public class StudentModel
{
public int StudenId {get; set;}
public string StudenName {get; set;}
public bool HasSiblings {get; set;}
public List<SiblingModel> SiblingDetails {get; set;}
}
Sibling Model同级 Model
public class SiblinModel
{
public int SiblingId {get; set;}
[Required]
public string SiblingName {get; set;}
}
Now, I want to validate SiblingModel only if HasSibling in StudentModel is set to true.现在,我只想在 StudentModel 中的 HasSibling 设置为 true 时验证 SiblingModel。
Note : I do not want to use IValidatableObject and then validate each and every property of SiblingModel.注意:我不想使用 IValidatableObject 然后验证 SiblingModel 的每个属性。 I have used the above models only for example.
我仅以上述模型为例。 In the actual model, I have validation for around 10-12 fields.
在实际的 model 中,我验证了大约 10-12 个字段。 So writing validation checks for each and every attribute would be a tedious task.
因此,为每个属性编写验证检查将是一项乏味的任务。
Is there a way through which I can validate the entire model conditionally ie if HasSibling is set to true then only validate Sibling Model.有没有一种方法可以有条件地验证整个 model,即如果 HasSibling 设置为 true,则仅验证 Sibling Model。
Also, I am using action filter in my project to check for validations in each and every request automatically.另外,我在我的项目中使用操作过滤器来自动检查每个请求中的验证。
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);
}
}
}
So is there any way around or I have to manually write Validations check using IValidatableObject.那么有什么办法,或者我必须使用 IValidatableObject 手动编写验证检查。
Well, your question is ambiguous:好吧,你的问题是模棱两可的:
Is there a way through which I can validate the entire model conditionally ie if HasSibling is set to true then only validate Sibling Model.
有没有一种方法可以有条件地验证整个 model,即如果 HasSibling 设置为 true,则仅验证 Sibling Model。
If you want to validate the entire model based on a property, using ActionFilter
is a good choice.如果要基于某个属性验证整个 model,使用
ActionFilter
是一个不错的选择。 If you want conditionally validate a property based on another property below solution works.如果您想有条件地验证基于以下解决方案的另一个属性的属性。
Here is an example of RequiredIf
attribute:下面是
RequiredIf
属性的示例:
public sealed class RequiredIfAttribute : ValidationAttribute
{
private readonly RequiredAttribute _innerRequiredAttribute = new RequiredAttribute();
private readonly string _dependentPropertyName;
private readonly object[] _targetValues;
public RequiredIfAttribute(string dependentPropertyName, params object[] targetValues)
{
_dependentPropertyName = dependentPropertyName;
_targetValues = targetValues;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var containerType = validationContext.ObjectInstance.GetType();
var field = containerType.GetProperty(_dependentPropertyName);
if (field == null)
return ValidationResult.Success;
// get the value of the dependent property
var dependentValue = field.GetValue(validationContext.ObjectInstance, null);
foreach (var obj in _targetValues)
{
// compare the value against the target value
if (dependentValue.GetHashCode().Equals(obj.GetHashCode()))
{
// match => means we should try validating this field
if (!_innerRequiredAttribute.IsValid(value))
// validation failed - return an error
return new ValidationResult(ErrorMessage, new[] { validationContext.MemberName });
}
}
return ValidationResult.Success;
}
}
And in your model:在您的 model 中:
public class StudentModel
{
public int StudenId {get; set;}
public string StudenName {get; set;}
public bool HasSiblings {get; set;}
[RequiredIf(nameof(HasSiblings), true)]
public List<SiblingModel> SiblingDetails {get; set;}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.