使用FluentValidation实现C#数据验证,通过分离验证逻辑与模型、支持复杂规则和ASP.NET Core集成,提升代码可维护性与安全性。

在C#中实现数据库的数据验证,通常是在数据进入数据库之前进行模型层面的校验。使用 FluentValidation 是一种优雅且可维护的方式,它将验证逻辑与业务模型分离,支持链式语法,便于编写复杂的验证规则。
FluentValidation 是一个开源的 .NET 验证库,相比传统的数据注解(Data Annotations),它具有以下优势:
通过 NuGet 安装必要的包:
Install-Package FluentValidation如果在 ASP.NET Core 项目中使用,还建议安装:
Install-Package FluentValidation.AspNetCore假设有一个用户实体:
public class User
{
    public string Name { get; set; }
    public string Email { get; set; }
    public int Age { get; set; }
}
为 User 类创建一个继承自 AbstractValidator<T> 的验证器:
using FluentValidation;
<p>public class UserValidator : AbstractValidator<User>
{
public UserValidator()
{
RuleFor(x => x.Name)
.NotEmpty().WithMessage("姓名不能为空")
.MaximumLength(50).WithMessage("姓名不能超过50个字符");</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">    RuleFor(x => x.Email)
        .NotEmpty().WithMessage("邮箱不能为空")
        .EmailAddress().WithMessage("邮箱格式不正确");
    RuleFor(x => x.Age)
        .InclusiveBetween(18, 100).WithMessage("年龄必须在18到100之间");
}}
在实际调用数据库前执行验证:
var user = new User { Name = "Tom", Email = "tom@example.com", Age = 16 };
<p>var validator = new UserValidator();
var result = validator.Validate(user);</p><p>if (!result.IsValid)
{
foreach (var failure in result.Errors)
{
Console.WriteLine($"错误:{failure.PropertyName} - {failure.ErrorMessage}");
}
}
else
{
// 验证通过,可以安全写入数据库
dbContext.Users.Add(user);
dbContext.SaveChanges();
}
在 Program.cs 或 Startup.cs 中注册服务:
builder.Services.AddControllers()
                .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<UserValidator>());
这样,在 Controller 接收模型时会自动触发验证:
[HttpPost]
public IActionResult CreateUser(User user)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">// 保存到数据库
return Ok();}
例如,确保 Email 在数据库中唯一(需访问 DbContext):
public class UserValidator : AbstractValidator<User>
{
    private readonly YourDbContext _context;
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">public UserValidator(YourDbContext context)
{
    _context = context;
    RuleFor(x => x.Email)
        .Must(BeUniqueEmail)
        .WithMessage("该邮箱已被使用");
}
private bool BeUniqueEmail(string email)
{
    return !_context.Users.Any(u => u.Email == email);
}}
注意:需要将验证器注册为 Scoped 或 Transient,并注入 DbContext。
使用 FluentValidation 可以让 C# 项目中的数据验证更加清晰、可读和可维护。它特别适合在进入数据库前对输入数据做严格校验,防止无效或恶意数据入库。结合 ASP.NET Core 使用,还能实现自动化请求验证,提升开发效率。
基本上就这些——不复杂但容易忽略细节,比如异步验证、集合验证、嵌套对象验证等,可根据需要进一步深入。
以上就是如何用C#实现数据库的数据验证?使用FluentValidation?的详细内容,更多请关注php中文网其它相关文章!
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
                
                                
                                
                                
                                
                                
                                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号