您现在的位置是:网站首页> 编程资料编程资料
ASP.NET MVC5验证系列之服务端验证_实用技巧_
2023-05-24
392人已围观
简介 ASP.NET MVC5验证系列之服务端验证_实用技巧_
这篇文章,我将会说到,使用数据注解API来进行服务端验证。ASP.NET MVC 框架在执行的时候,验证所有传递到控制器的数据,如果验证失败就把错误消息,填充到ModelState对象中,并且把这个对象传递给控制器,然后控制器中的方法,根据Modelstate的状态来判断,是否验证失败还是验证通过。
在这里,我将会使用两种方法来验证数据的合法性,一个是手动添加错误消息到ModelState对象中,另外一个方法是使用数据注解【Data Annotation】 API,来做。
先来看看使用手动验证的方式吧:
我们新建一个空白的MVC项目:添加一个Student实体:
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Server_Side_Validation_IN_MVC.Models { public class Student { public string Name { get; set; } public string Email { get; set; } } } 然后添加一个Student控制器:
using Server_Side_Validation_IN_MVC.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Web; using System.Web.Mvc; namespace Server_Side_Validation_IN_MVC.Controllers { public class StudentController : Controller { // GET: Student public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(Student model) { //服务端验证,方法一,手动添加错误消息到ModelState对象中 //如果Name是空的 if (string.IsNullOrEmpty(model.Name)) { ModelState.AddModelError("Name", "Name is required"); } //如果Email是空的 if (string.IsNullOrEmpty(model.Email)) { ModelState.AddModelError("Email", "Email is required"); } else { string emailRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" + @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" + @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"; Regex re = new Regex(emailRegex); //Email不为空的时候,但格式不合法 if (!re.IsMatch(model.Email)) { ModelState.AddModelError("Email", "Email is not valid"); } } //实体验证通过 if (ModelState.IsValid) { ViewBag.Name = model.Name; ViewBag.Email = model.Email; } return View(model); } } } 创建Index视图:
@model Server_Side_Validation_IN_MVC.Models.Student @{ Layout = null; } Index @using (Html.BeginForm()) { //使用ViewData.ModelState.IsValid来判断ModelState的状态 if (ViewData.ModelState.IsValid) { if (ViewBag.Name != null) { Name:@ViewBag.Name
Email:@ViewBag.Email } } } 然后,修改一下默认的路由:
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Student", action = "Index", id = UrlParameter.Optional } ); } 运行之后,报错。查找了一下原因,修改了一下视图代码:

运行之后,

接着验证一下,Name不为空,Email输入非法格式的数据:

最后验证一下,输入合法的数据:

好了,现在看看第二种方式,使用数据注解来进行服务端验证:
新建一个类:避免混淆,
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace Server_Side_Validation_IN_MVC.Models { public class StudentServer { [Required(ErrorMessage="Name为必填项")] public string Name { get; set; } [Required(ErrorMessage="电子邮件必须")] [EmailAddress(ErrorMessage="电子邮件格式不对")] public string Email { get; set; } } } 在控制器中新建两个方法:
public ActionResult SeverSideIndex() { return View(); } [HttpPost] public ActionResult SeverSideIndex(StudentServer model) { if (ModelState.IsValid) { ViewBag.Name = model.Name; ViewBag.Email = model.Email; } return View(); } 对应的视图:
@model Server_Side_Validation_IN_MVC.Models.StudentServer @{ Layout = null; } @if (ViewData.ModelState.IsValid) { if (ViewBag.Name != null) { Name:@ViewBag.Name
Email:@ViewBag.Email } } SeverSideIndex @using (Html.BeginForm()) { @Html.ValidationSummary(true) } 
首先验证,都为空的情况:

Name不为空,Email为空

Name不为空,Email输入非法格式数据

两个都输入合法的数据:

好了,以上就是MVC中服务端验证了,我们一般是使用第二种,来进行验证。也就是数据注解。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
相关内容
- ASP.NET MVC5验证系列之客户端验证_实用技巧_
- ASP.NET MVC4使用MongoDB制作相册管理_实用技巧_
- VS2015 Update2 构建 Android 程序问题汇总_实用技巧_
- VS2015 update2安装历程_实用技巧_
- VS2015在升级到Update2之后运行Cordova项目异常的解决方案_实用技巧_
- 简单谈谈.NET Core跨平台开发_实用技巧_
- 云服务器下搭建ASP.NET Core环境_实用技巧_
- Linux(Ubuntu)下搭建ASP.NET Core环境_实用技巧_
- Ubuntu16.04系统配置.net core环境_实用技巧_
- .net mvc超过了最大请求长度的解决方法_实用技巧_
