当前位置:首页 > C# > 正文

ASP.NET Core验证入门指南(使用DataAnnotations实现模型验证)

在开发 ASP.NET Core 应用程序时,确保用户输入的数据合法、安全是至关重要的。为此,.NET 提供了一套强大而简洁的验证机制——DataAnnotations。本教程将手把手教你如何在 ASP.NET Core 项目中使用 DataAnnotations 进行模型验证,即使是编程小白也能轻松上手!

什么是 DataAnnotations?

DataAnnotations 是 .NET 中一组用于定义数据验证规则的特性(Attributes)。通过在模型类的属性上添加这些特性,你可以自动对用户提交的数据进行验证,而无需编写大量手动校验代码。

ASP.NET Core验证入门指南(使用DataAnnotations实现模型验证) Core验证 DataAnnotations验证 模型验证 C#数据注解 第1张

常用 DataAnnotations 验证特性

以下是一些最常用的验证特性:

  • [Required]:表示该字段为必填项。
  • [StringLength(maximumLength)]:限制字符串的最大长度。
  • [EmailAddress]:验证是否为有效邮箱格式。
  • [Range(min, max)]:限制数值范围。
  • [RegularExpression(pattern)]:使用正则表达式进行自定义验证。

实战:创建一个带验证的用户注册模型

假设我们要创建一个用户注册表单,需要验证用户名、邮箱和年龄。下面是如何使用 C# 数据注解 实现模型验证。

using System.ComponentModel.DataAnnotations;public class RegisterModel{    [Required(ErrorMessage = "用户名不能为空")]    [StringLength(20, MinimumLength = 3, ErrorMessage = "用户名长度必须在3到20个字符之间")]    public string Username { get; set; }    [Required(ErrorMessage = "邮箱不能为空")]    [EmailAddress(ErrorMessage = "请输入有效的邮箱地址")]    public string Email { get; set; }    [Range(18, 100, ErrorMessage = "年龄必须在18到100岁之间")]    public int Age { get; set; }}  

在控制器中处理验证

在 ASP.NET Core 的 Controller 中,框架会自动根据模型上的 DataAnnotations 特性进行验证。你只需检查 ModelState.IsValid 即可判断数据是否合法。

[HttpPost]public IActionResult Register(RegisterModel model){    if (!ModelState.IsValid)    {        // 验证失败,返回错误信息        return View(model);    }    // 验证通过,执行注册逻辑    return RedirectToAction("Success");}  

在 Razor 视图中显示验证错误

在视图(View)中,你可以使用 Tag Helpers 自动显示验证错误信息:

<form asp-action="Register" method="post">    <div class="hw8a91-3d14-223a-df22 form-group">        <label asp-for="Username"></label>        <input asp-for="Username" class="hw3d14-223a-df22-4eb5 form-control" />        <span asp-validation-for="Username" class="hw223a-df22-4eb5-9e56 text-danger"></span>    </div>    <div class="hwdf22-4eb5-9e56-c438 form-group">        <label asp-for="Email"></label>        <input asp-for="Email" class="hw4eb5-9e56-c438-ee3c form-control" />        <span asp-validation-for="Email" class="hw9e56-c438-ee3c-dc25 text-danger"></span>    </div>    <div class="hwc438-ee3c-dc25-f040 form-group">        <label asp-for="Age"></label>        <input asp-for="Age" class="hwee3c-dc25-f040-67f6 form-control" />        <span asp-validation-for="Age" class="hwdc25-f040-67f6-4c88 text-danger"></span>    </div>    <button type="submit" class="hw96f6-bef2-7977-28e0 btn btn-primary">注册</button></form><!-- 启用客户端验证 --><partial name="_ValidationScriptsPartial" />  

注意:最后一行 <partial name="_ValidationScriptsPartial" /> 会引入 jQuery 和验证脚本,使验证在浏览器端(客户端)也生效,提升用户体验。

总结

通过使用 ASP.NET Core 验证DataAnnotations,你可以轻松实现前后端一致的数据校验,保障应用的安全性和健壮性。无论是简单的必填字段,还是复杂的自定义规则,DataAnnotations 都能帮你高效完成。

掌握这套机制后,你的 C# Web 开发效率将大幅提升。快在你的下一个项目中试试吧!

关键词回顾:ASP.NET Core验证DataAnnotations验证模型验证C#数据注解