简体   繁体   English

如何有条件地验证 ASP.NET 核心 Web ZDB974238714CA8DE634A7CE1D08 中的整个 model?

[英]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.

相关问题 如何在ASP.NET Core 2 Web API中仅验证模型状态的一部分 - How to validate only a part of Model State in asp.net core 2 web api 如何验证模型取决于使用ASP.NET Core Web API的布尔数据类型值 - How to validate model depends on bool datatype value using asp.net core web api 如何通过仅允许在 asp.net 核心 web Z8A35DA52ED1057271 的 Model 中分配的属性来验证请求正文 - How to Validate Request Body by allowing only attributes assigned in the Model of an asp.net core web api app 根据Model Asp.net Core API验证Json String - Validate Json String against Model asp.net core api 如何验证 asp.net 核心 3.0 web api 的获取请求中的参数? - How to Validate parameter in asp.net core 3.0 web api's get request? ASP.NET 核心 Web API - 如何创建用户并在验证期间验证是否存在 - ASP.NET Core Web API - How to create user and validate if not exist during validation ASP.NET 内核 Web API - 如何在 EF 中验证 EndDate 大于 StartDate - ASP.NET Core Web API - How to validate EndDate greater than StartDate in EF ASP.NET 内核 Web API - 如何使用数据注释根据指定值进行验证 - ASP.NET Core Web API - How to validate based on specified value using data annotation 如何验证 ASP.NET Core Web API 中必须有 2 个字段之一? - How to validate must have 1 of 2 fields in ASP.NET Core Web API? ASP.NET Core Web API 模型绑定行为更改 - ASP.NET Core Web API Model binding behavior change
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM