這篇文章將為大家詳細講解有關ASP.NET MVC5驗證之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 MVC5驗證之Fluent Validation的示例分析”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。