ASP.NET MVC5验证系列之Fluent Validation

所属分类: 网络编程 / ASP.NET 阅读数: 1813
收藏 0 赞 0 分享

前面两篇文章学习到了,服务端验证,和客户端的验证,但大家有没有发现,这两种验证各自都有弊端,服务器端的验证,验证的逻辑和代码的逻辑混合在一起了,如果代码量很大的话,以后维护扩展起来,就不是很方便。而客户端的验证,必须要启用客户端验证,也就是在配置文件中配置相应的节点,并且还要引入Jquery插件。如果人为的在浏览器上,禁用了js脚本,那么客户端验证就不起作用了,所以在这里,我将继续学习另外一个验证,也就是Fluent Validation。

Fluent Validation是一个开源的.NET类库,它使用Fluent接口和lambda表达式,来为实体做验证。Fluent Validation是专门为实体做验证使用的。它的优点是:把验证逻辑和你代码的业务逻辑分别开了。这就是AOP的思想。就是横切关注点。你只需要关注某一个模块。这样就保证了代码的纯洁度。

Fluent Validation开源地址:https://github.com/JeremySkinner/fluentvalidation 

例句:
Aspect-oriented program is a new software development paradigm that enables modular implementation of cross-cutting concerns,and poses difficulties for slicing of aspect-oriented programs.
面向方面程序设计作为一种新的软件开发范型,能够实现横切关注点的模块化,其特有的语言元素和功能为切片增加了难度。
好了,废话太多,直接进入正题,
首先我们新建一个空白的MVC项目:在Model文件夹下新建一个类Customer: 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Server_Side_Validation_IN_MVC.Models
{
 public class Customer
 {
  public string Name { get; set; }
  public string Email { get; set; }
 }
}

然后新建一个文件夹Validator,在里面添加一个类CustomerValidator 

既然是要使用Fluent Validation,那么就是要引用它的类库了。 

CustomerValidator类中,继承AbstractValidator抽象类,(PS:这里和EF中的Fluent API类似,EF中是继承EntityTypeConfiguration类) 

using FluentValidation;
using Server_Side_Validation_IN_MVC.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Server_Side_Validation_IN_MVC.Validator
{
 public class CustomerValidator:AbstractValidator<Customer>
 {
  public CustomerValidator()
  {
   RuleFor(s => s.Name).NotEmpty().WithMessage("名字不能为空");
   RuleFor(s => s.Email).NotEmpty().WithMessage("电子邮件不能为空");
   RuleFor(s => s.Email).EmailAddress().WithMessage("电子邮件格式不合法");
  }
 }
}

控制器中的代码: 

using FluentValidation.Results;
using Server_Side_Validation_IN_MVC.Models;
using Server_Side_Validation_IN_MVC.Validator;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Server_Side_Validation_IN_MVC.Controllers
{
 public class CustomerController : Controller
 {
  // GET: Customer
  public ActionResult Index()
  {
   return View();
  }

  [HttpPost]
  public ActionResult Index(Customer model)
  {
   CustomerValidator validator = new CustomerValidator();
   ValidationResult result = validator.Validate(model);

   if (result.IsValid)
   {
    ViewBag.Name = model.Name;
    ViewBag.Email = model.Email;
   }
   else
   {
    foreach (var item in result.Errors)
    {
     ModelState.AddModelError(item.PropertyName, item.ErrorMessage);
    }
   }
   return View(model);
  }
 }
}

 

修改一下,默认的路由:

public static void RegisterRoutes(RouteCollection routes)
  {
   routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

   routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Customer", action = "Index", id = UrlParameter.Optional }
   );
  }

什么都不输入,直接点击Create:

输入Name,不输入Email

输入Name,Email输入非法的数据

输入合法的数据:

这里就完成了Fluent Validation验证。大家可以看到,这样的验证是不是干净简洁多了,配置信息都在一个类中,方便维护和扩展。不想数据注解那样,把验证信息和实体混合了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

ASP.NET 水晶报表打印功能实现代码

ASP.NET下的水晶报表打印,据我所知有以下几种办法可以打印
收藏 0 赞 0 分享

ASP.Net 图片存入数据库的实现代码

在很多时候,我们有这样的需求:把图片存入到数据库当中。在一些应用程序中,我们可能有一些敏感的资料,由于存储在文件系统(file system)中的东西,将很容易被某些用户盗取,所以这些数据不能存放在文件系统中。
收藏 0 赞 0 分享

让Silverlight 2.0动画动起来Making Silverlight 2.0 animation Start(不能运动原因)

Microsoft Expression Blend 2 制作动画个人感觉倒像3DMAX 可以自动捕捉关键帧
收藏 0 赞 0 分享

asp.net Reporting Service在Web Application中的应用

由于我们这个项目中使用微软的报表服务(Reporting Services)作为报表输出工具,本人也对它进行一点点研究,虽没有入木三分,但这点知识至少可以在大部分Reporting Service的场景中应用。
收藏 0 赞 0 分享

C# 文件上传 默认最大为4M的解决方法

.net中默只能上传小于4m的文件,大于4M将无法显示页面.那么如何设置来使imputfile能上传更大的文件呢
收藏 0 赞 0 分享

asp.net 购物车实现详细代码

asp.net 购物车实现详细代码
收藏 0 赞 0 分享

asp.net repeater实现批量删除时注册多选框id到客户端

repeater批量删除时注册多选框id到客户端的实现代码
收藏 0 赞 0 分享

asp.net aspnetpager分页统计时与实际不符的解决办法

最近分页方面根据实际需要修改了一些函数
收藏 0 赞 0 分享

iis 服务器应用程序不可用的解决方法

访问页面时提示 服务器应用程序不可用,大家可以按照下面的方法重新注册下,应该能好点
收藏 0 赞 0 分享

asp.net button 绑定多个参数

asp.net button 绑定多个参数的代码
收藏 0 赞 0 分享
查看更多