简体   繁体   English

在ASP.NET Core中查看模型和Fluent验证

[英]View models and Fluent Validation in ASP.NET Core

How can we Validate Models passed from Views to our API Controllers in ASP.NET Core. 我们如何验证从视图传递到ASP.NET Core中的API控制器的模型。 Is there a tool like FluentValidation or any similar approach that can be customized to return our errors and messages back to the client apps? 是否有像FluentValidation这样的工具或任何类似的方法可以自定义以将我们的错误和消息返回给客户端应用程序?

You make use of the IValidatableObject interface. 您可以使用IValidatableObject接口。 Then create a abstract base class and let your classes inherit from it. 然后创建一个抽象基类,让你的类继承它。 You will need to add a reference to System.ComponentModel.DataAnnotations. 您需要添加对System.ComponentModel.DataAnnotations的引用。 You can add helper methods to the base class as well. 您也可以将辅助方法添加到基类。

public abstract class ValidatingBase : IValidatableObject
{
        public bool IsNullOrEmpty(string property)
        {
            return string.IsNullOrEmpty(property);
        }

            #region IValidatableObject

        public abstract IEnumerable<ValidationResult> Validate(ValidationContext validationContext);

        public IEnumerable<ValidationResult> Validate()
        {
            var validationErrors = new List<ValidationResult>();
            var ctx = new ValidationContext(this, null, null);
            Validator.TryValidateObject(this, ctx, validationErrors, true);
            return validationErrors;
        }

        #endregion IValidatableObject
}

Then your class that inherits from the above 然后你的类继承了上面的内容

public class InsertCompanies : ValidatingBase
{
   public string CompanyName { get; set; }

   #region ValidatingCommandBase

        public override IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (this.IsNullOrEmpty(this.Name))
            {
                yield return new ValidationResult($"{nameof(this.Name)} field can't be null or empty.", new[] { nameof(this.Name) });
            }

            if (this.Name?.Length > 100)
            {
                yield return new ValidationResult($"{nameof(this.Name)} field can't be greater than 100 characters.", new[] { nameof(this.Name) });
            }
        }

        #endregion ValidatingCommandBase
}

There is not much limitation as to what you can do with the above implementation. 对于您可以使用上述实现做什么没有太多限制。 Perhaps it is a viable option for you? 也许这对你来说是一个可行的选择?

Asp.Net Core gladly will call the method for you, more information can be found at the link below. Asp.Net Core很乐意为您调用该方法,更多信息可以在下面的链接中找到。 https://docs.asp.net/en/latest/mvc/models/validation.html https://docs.asp.net/en/latest/mvc/models/validation.html

   [HttpPost]

    public ActionResult Register(RegisterViewModel model)
    {
  // if the validation doesn't match then load same view again with errors
        if (!ModelState.IsValid) 
        {
            return View(model);
        }



    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM