博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ASP.NET MVC中使用FluentValidation验证实体
阅读量:7235 次
发布时间:2019-06-29

本文共 6690 字,大约阅读时间需要 22 分钟。

  1、FluentValidation介绍

  FluentValidation是与ASP.NET DataAnnotataion Attribute验证实体不同的数据验证组件,提供了将实体与验证分离开来的验证方式,同时FluentValidation还提供了表达式链式语法。

  2、安装FluentValidation

  FluentValidation地址:

  使用Visual Studio的管理NuGet程序包安装FluentValidation及FluentValidation.Mvc

  3、通过ModelState使用FluentValidation验证

  项目解决方案结构图:

  

  实体类Customer.cs:

using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace Libing.Portal.Web.Models.Entities{    public class Customer    {        public int CustomerID { get; set; }        public string CustomerName { get; set; }        public string Email { get; set; }        public string Address { get; set; }        public string Postcode { get; set; }        public float? Discount { get; set; }        public bool HasDiscount { get; set; }    }}

  数据验证类CustomerValidator.cs:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using FluentValidation;using Libing.Portal.Web.Models.Entities;namespace Libing.Portal.Web.Models.Validators{    public class CustomerValidator : AbstractValidator
{ public CustomerValidator() { RuleFor(customer => customer.CustomerName).NotNull().WithMessage("客户名称不能为空"); RuleFor(customer => customer.Email) .NotEmpty().WithMessage("邮箱不能为空") .EmailAddress().WithMessage("邮箱格式不正确"); RuleFor(customer => customer.Discount) .NotEqual(0) .When(customer => customer.HasDiscount); RuleFor(customer => customer.Address) .NotEmpty() .WithMessage("地址不能为空") .Length(20, 50) .WithMessage("地址长度范围为20-50字节"); } }}

  控制器类CustomerController.cs:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using FluentValidation.Results;using Libing.Portal.Web.Models.Entities;using Libing.Portal.Web.Models.Validators;namespace Libing.Portal.Web.Controllers{    public class CustomerController : Controller    {        public ActionResult Index()        {            return View();        }        public ActionResult Create()        {            return View();        }        [HttpPost]        public ActionResult Create(Customer customer)        {            CustomerValidator validator = new CustomerValidator();            ValidationResult result = validator.Validate(customer);            if (!result.IsValid)            {                result.Errors.ToList().ForEach(error =>                {                    ModelState.AddModelError(error.PropertyName, error.ErrorMessage);                });            }            if (ModelState.IsValid)            {                return RedirectToAction("Index");            }            return View(customer);        }    }}

  View页面Create.cshtml,该页面为在添加View时选择Create模板自动生成:

@model Libing.Portal.Web.Models.Entities.Customer@{    Layout = null;}    
Create @using (Html.BeginForm()) { @Html.AntiForgeryToken()

Customer


@Html.ValidationSummary(true)
@Html.LabelFor(model => model.CustomerName, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.CustomerName) @Html.ValidationMessageFor(model => model.CustomerName)
@Html.LabelFor(model => model.Email, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Email) @Html.ValidationMessageFor(model => model.Email)
@Html.LabelFor(model => model.Address, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Address) @Html.ValidationMessageFor(model => model.Address)
@Html.LabelFor(model => model.Postcode, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Postcode) @Html.ValidationMessageFor(model => model.Postcode)
@Html.LabelFor(model => model.Discount, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Discount) @Html.ValidationMessageFor(model => model.Discount)
@Html.LabelFor(model => model.HasDiscount, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.HasDiscount) @Html.ValidationMessageFor(model => model.HasDiscount)
}

  运行效果:

  

  4、通过设置实体类Attribute与验证类进行验证

  修改实体类Customer.cs:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using FluentValidation.Attributes;using Libing.Portal.Web.Models.Validators;namespace Libing.Portal.Web.Models.Entities{    [Validator(typeof(CustomerValidator))]    public class Customer    {        public int CustomerID { get; set; }        public string CustomerName { get; set; }        public string Email { get; set; }        public string Address { get; set; }        public string Postcode { get; set; }        public float? Discount { get; set; }        public bool HasDiscount { get; set; }    }}

  修改Global.asax.cs:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using System.Web.Routing;using FluentValidation.Attributes;using FluentValidation.Mvc;namespace Libing.Portal.Web{    public class MvcApplication : System.Web.HttpApplication    {        protected void Application_Start()        {            AreaRegistration.RegisterAllAreas();            RouteConfig.RegisterRoutes(RouteTable.Routes);            // FluentValidation设置            DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;            ModelValidatorProviders.Providers.Add(new FluentValidationModelValidatorProvider(new AttributedValidatorFactory()));        }    }}

  

转载于:https://www.cnblogs.com/libingql/p/3801704.html

你可能感兴趣的文章
LVS集群实战
查看>>
linux虚拟化管理
查看>>
<?php $sql = <<<EOF 。。。。EOF;?>这种写法是什么意思
查看>>
[精讲]15-Winodws Server 2012 工作文件夹
查看>>
java.lang.ClassCastException: org.apache.catalina.util.DefaultAnnotationProcessor 访问jsp报错-过滤器报错...
查看>>
如何更改Exchange服务器的传输队列数据库路径
查看>>
未来图灵发布《AI明星企业家热搜榜》
查看>>
Linux存储管理及硬盘分区、格式化、挂载
查看>>
Linux服务器时间不准确
查看>>
【AD】清楚windows下的不同凭据缓存
查看>>
没有如果,只需要去尝试
查看>>
LINUX下删除用户与主目录
查看>>
Remote Listener Server side Connect-Time Load Balancing
查看>>
程序开发时编写sql语句的注意事项
查看>>
Oracle 12c新特性对于业务上的一些影响总结
查看>>
Xenserver HA功能配置文档
查看>>
lamp+rsyslog+loganalyzer的安装配置
查看>>
通联数据是如何使用Docker+Rancher构建自动发布管道的?
查看>>
c#调用cxf的代码
查看>>
Linux下openssh升级安装配置
查看>>