当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET全栈开发教程之在MVC中使用服务端验证的方法

ASP.NET全栈开发教程之在MVC中使用服务端验证的方法

2018年08月08日  | 移动技术网IT编程  | 我要评论

情海狂龙,winrar是什么东西,楚网

前言

我们在控制台中基本的了解了fluentvalidation是如何简洁,优雅的完成了对实体的验证工作,今天我们将在实战项目中去应用它。

首先我们创建一个asp.net mvc项目,本人环境是vs2017,

创建成功后通过在nuget中使用 install-package fluentvalidation -version 7.6.104 安装fluentvalidation

在model文件夹中添加两个实体address 和 person

public class address
 {
 public string home { get; set; }

 public string phone { get; set; }
 }
public class person
 {
 /// <summary>
 /// 姓名
 /// </summary>
 public string name { get; set; }
 /// <summary>
 /// 年龄
 /// </summary>
 public int age { get; set; }
 /// <summary>
 /// 性别
 /// </summary>
 public bool sex { get; set; }

 /// <summary>
 /// 地址
 /// </summary>
 public address address { get; set; }
 }

紧接着创建实体的验证器

public class addressvalidator : abstractvalidator<address>
 {
 public addressvalidator()
 {
 this.rulefor(m => m.home)
 .notempty()
 .withmessage("家庭住址不能为空");

 this.rulefor(m => m.phone)
 .notempty()
 .withmessage("手机号码不能为空");
 }
 }
public class personvalidator : abstractvalidator<person>
 {
 public personvalidator()
 {
 this.rulefor(p => p.name)
 .notempty()
 .withmessage("姓名不能为空");

 this.rulefor(p => p.age)
 .notempty()
 .withmessage("年龄不能为空");

 this.rulefor(p => p.address)
 .setvalidator(new addressvalidator());

 }
 }

为了更好的管理验证器,我建议将使用一个manager者来管理所有验证器的实例。如validatorhub

public class validatorhub
 {
 public addressvalidator addressvalidator { get; set; } = new addressvalidator();

 public personvalidator personvalidator { get; set; } = new personvalidator();
 }

现在我们需要创建一个页面,在默认的homecontroller 控制器下添加2个action:validatortest,他们一个用于展示页面,另一个则用于提交。

[httpget]
 public actionresult validatortest()
 {
 return view();
 }

 [httppost]
 public actionresult validatortest(person model)
 {
 return view();
 }

为 validatortest 添加视图,选择create模板,实体为person

将默认的@html全部删掉,因为在我们本次介绍中不需要,我们的目标是搭建一个前后端分离的项目,而不要过多的依赖于mvc。

最终我们将表单改写成了

@using (html.beginform())
{
 @html.antiforgerytoken()

 <div class="form-horizontal">
 <h4>person</h4>
 <hr />
 @html.validationsummary(true, "", new { @class = "text-danger" })
 <div class="form-group">
 <label for="name" class="control-label col-md-2">姓名</label>
 <div class="col-md-10">
 <input type="text" name="name" class="form-control" />
 </div>
 </div>

 <div class="form-group">
 <label for="age" class="control-label col-md-2">年龄</label>
 <div class="col-md-10">
 <input type="text" name="age" class="form-control" />
 </div>
 </div>

 <div class="form-group">
 <label for="home" class="control-label col-md-2">住址</label>
 <div class="col-md-10">
 <input type="text" name="address.home" class="form-control" />
 </div>
 </div>

 <div class="form-group">
 <label for="phone" class="control-label col-md-2">电话</label>
 <div class="col-md-10">
 <input type="text" name="address.phone" class="form-control" />
 </div>
 </div>

 <div class="form-group">
 <label for="sex" class="control-label col-md-2">性别</label>
 <div class="col-md-10">
 <div class="checkbox">
 <input type="checkbox" name="sex" />
 </div>
 </div>
 </div>

 <div class="form-group">
 <div class="col-md-offset-2 col-md-10">
 <input type="submit" value="create" class="btn btn-default" />
 </div>
 </div>
 </div>
}

注意,由于我们的实体person中存在复杂类型address,我们都知道,表单提交默认是key:value形式,而在传统表单的key:value中,我们无法实现让key为address的情况下value为一个复杂对象,因为input一次只能承载一个值,且必须是字符串。实际上mvc中存在模型绑定,此处不作过多介绍(因为我也忘记了-_-||)。

简单的说就是他能根据你所需要类型帮我们自动尽可能的转换,我们目前只要知道如何正确使用,在address中存在home属性和phone属性,我们可以将表单的name设置为address.home,mvc的模型绑定会将address.home解析到对象address上的home属性去。

简单的校验方式我也不过多介绍了。再上一章我们已经了解到通过创建一个实体的验证器来对实体进行验证,然后通过isvalid属性判断是否验证成功。对,没错,对于大家来说这太简单了。但我们每次校验都创建一个验证器是否显得有点麻烦呢?不要忘了我们刚刚创建了一个validatorhub,我们知道控制器默认继承自controller,如果我们想为控制器扩展一些能力呢?现在我要创建一个controllerex了,并继承自controller。

public class controllerex : controller
 {
 protected dictionary<string, string> dicerror { get; set; } = new dictionary<string, string>();

 protected validatorhub validatorhub { get; set; } = new validatorhub();

 protected override void onactionexecuted(actionexecutedcontext filtercontext)
 {
 base.onactionexecuted(filtercontext);
 viewdata["error"] = dicerror;
 }

 protected void validatorerrorhandler(validationresult result)
 {
 foreach (var failure in result.errors)
 {
 if (!this.dicerror.containskey(failure.propertyname))
 {
  this.dicerror.add(failure.propertyname, failure.errormessage);
 }
 }
 }
 }

在controllerex里我创建了一个validatorhub属性,正如其名,他内部存放着各种验证器实体呢。有了它,我们可以在需要验证的action中通过this.validatorhub.具体验证器就能完成具体验证工作了,而不需要再去每次new 一个验证器。

同样我定义了一个dicerror的键值对集合,他的键和值类型都是string。key是验证失败的属性名,而value则是验证失败后的错误消息,它是用来存在验证的结果的。

在这里我还定义了一个validatorerrorhandler的方法,他有一个参数是验证结果,通过名称我们大致已经猜到功能了,验证错误的处理,对验证结果的错误信息进行遍历,并将错误信息添加至dicerror集合。

最终我需要将这个dicerror传递给view,简单的办法是viewdata["error"] 但我不想在每个页面都去这么干,因为这使我要重复多次写这行代码,我会厌倦它的。很棒的是mvc框架为我们提供了filter(有的地方也称函数钩子,切面编程,过滤器),能够方便我们在生命周期的不同阶段进行控制,很显然,我的需求是在每次执行完action后要在末尾添加一句viewdata["error"]=dicerror。于是我重写了onactionexecuted方法,仅添加了 viewdata["error"] = dicerror;

现在我只需要将homecontroller继承自controllerex即可享受以上所有功能了。

现在基本工作基本都完成了,但我们还忽略了一个问题,我错误是存在了viewdata["error"]里传递给view,只不过难道我们在验证错误的时候在页面显示一个错误列表?像li一样?这显然不是我们想要的。我们还需要一个帮助我们合理的显示错误信息的函数。在razor里我们可以对htmlhelper进行扩展。于是我为htmlhelper扩展了一个方法validatormessagefor

public static class validatorhelper
 {
 public static mvchtmlstring validatormessagefor(this htmlhelper htmlhelper, string property, object error)
 {
 var dicerror = error as dictionary<string, string>;

 if (dicerror == null) //没有错误
 {
 // 不会等于空
 }
 else
 {
 if (dicerror.containskey(property))
 {
  return new mvchtmlstring(string.format("<p>{0}</p>", dicerror[property]));
 }
 }
 return new mvchtmlstring("");
 }
 }

在validatormessaegfor里需要2个参数property 和 error

前者是需要显示的错误属性名,后者则是错误对象即viewdata["error"],功能很简单,在发现错误对象里存在key为错误属性名的时候将value用一个p标签包裹起来返回,value即为错误属性所对应的错误提示消息。

现在我们还需要在view每一个input下添加一句如: @html.validatormessagefor("name", viewdata["error"])即可。

@using (html.beginform())
{
 @html.antiforgerytoken()

 <div class="form-horizontal">
 <h4>person</h4>
 <hr />
 @html.validationsummary(true, "", new { @class = "text-danger" })
 <div class="form-group">
 <label for="name" class="control-label col-md-2">姓名</label>
 <div class="col-md-10">
 <input type="text" name="name" class="form-control" />
 @html.validatormessagefor("name", viewdata["error"])
 </div>
 </div>

 <div class="form-group">
 <label for="age" class="control-label col-md-2">年龄</label>
 <div class="col-md-10">
 <input type="text" name="age" class="form-control" />
 @html.validatormessagefor("name", viewdata["error"])
 </div>
 </div>

 <div class="form-group">
 <label for="home" class="control-label col-md-2">住址</label>
 <div class="col-md-10">
 <input type="text" name="address.home" class="form-control" />
 @html.validatormessagefor("address.home", viewdata["error"])
 </div>
 </div>

 <div class="form-group">
 <label for="phone" class="control-label col-md-2">电话</label>
 <div class="col-md-10">
 <input type="text" name="address.phone" class="form-control" />
 @html.validatormessagefor("address.phone", viewdata["error"])
 </div>
 </div>

 <div class="form-group">
 <label for="sex" class="control-label col-md-2">性别</label>
 <div class="col-md-10">
 <div class="checkbox">
  <input type="checkbox" name="sex" />
 </div>
 </div>
 </div>

 <div class="form-group">
 <div class="col-md-offset-2 col-md-10">
 <input type="submit" value="create" class="btn btn-default" />
 </div>
 </div>
 </div>
}

到此我们的所有基本工作都已完成

[httppost]
 public actionresult validatortest(person model)
 {
 var result = this.validatorhub.personvalidator.validate(model);
 if (result.isvalid)
 {
 return redirect("https://www.baidu.com");
 }
 else
 {
 this.validatorerrorhandler(result);
 }
 return view();
 }

通过我们在controllerex种的validatorhub来对实体person进行校验,如果校验成功了....这里没啥可干的就当跳转一下表示咯,否则的话调用ex中的validatorerrorhandler 将错误消息绑定到viewdata["error"]中去,这样就能在前端view渲染的时候将错误消息显示出来了。

接下来我们将程序跑起来。

正如大家所看到的,当我点击提交的时候 虽然只有电话没输入但其他三个表单被清空了,也许我们会觉得不爽,当然如果你需要那相信你在看完上述的错误信息绑定后一定也能解决这个问题的,但事实上,我们并不需要它,\(^o^)/~

为什么呢?因为我们还要前端验证啊,当前端验证没通过的时候根本无法发送到后端来,所以不用担心用户在一部分验证失败时已填写的表单数据被清空掉。

这里提到在表单提交时需要前端校验,既然有前端校验了为何还要我们做后台校验呢?不是脱了裤子放屁吗?事实上,前端校验的作用在于优化用户体验,减轻服务器压力,也可以防住君子,但绝不能防止小人,由于web客户端的不确定性,任何东西都可以模拟的。如果不做服务端验证,假如你的系统涉及金钱,也许那天你醒来就发现自己破产了。

来一个通过验证的。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网