ASP.NET Web API教程(五) 数据验证
如何使用web api 保证数据的有效性?实际项目中不是什么数据提交过来都是符合要求的,况且在天朝还有N多河蟹的关键字等等。所以以下内容就是增加web api 数据验证.
第一步修改 实体模型
public class UserInfo
{
public int Id { get; set; }
[Required]
[StringLength(20,ErrorMessage="名字太长了或者太短了",MinimumLength=4)]
public string Name { get; set; }
[RegularExpression(@"([2-5]\d)",ErrorMessage="年龄在20-50之间")]
public int Age { get; set; }
}
{
public int Id { get; set; }
[Required]
[StringLength(20,ErrorMessage="名字太长了或者太短了",MinimumLength=4)]
public string Name { get; set; }
[RegularExpression(@"([2-5]\d)",ErrorMessage="年龄在20-50之间")]
public int Age { get; set; }
}
注意:需要添加 System.ComponentModel.DataAnnotations; 引用
第二步增加Filter
public class ValidationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(
HttpStatusCode.BadRequest,
actionContext.ModelState);
}
}
}
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(
HttpStatusCode.BadRequest,
actionContext.ModelState);
}
}
}
注意:需要引入命名空间
using System.Web;
using System.Web.Http.Filters;
using System.Web.Http.ModelBinding;
using System.Web.Http.Controllers;
using System.Net.Http;
using System.Net;
using Newtonsoft.Json.Linq;
using System.Web.Http.Filters;
using System.Web.Http.ModelBinding;
using System.Web.Http.Controllers;
using System.Net.Http;
using System.Net;
using Newtonsoft.Json.Linq;
第三步 注册Filter
打开 webApiConfig
添加代码
config.Filters.Add(new Filters.ValidationAttribute());
第四步 编写页面
引入js/CSS
<link href="Content/Site.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="Scripts/knockout-2.1.0.js" type="text/javascript"></script>
<script src="Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="Scripts/knockout-2.1.0.js" type="text/javascript"></script>
<script src="Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
拷贝HTMLPage2的内容稍作修改
<label for="text">
名称</label>
<input id="name" name="name" data-val="true" data-val-required="是不是忘记输入名称了?" type="text"
value="" />
<span class="field-validation-valid" data-valmsg-for="name" data-valmsg-replace="true">
</span>
<label for="text">
年龄</label>
<input id="age" name="age" type="text" data-val="true" data-val-required="年龄也是必须输入的哦!"
value="" />
<span class="field-validation-valid" data-valmsg-for="age" data-valmsg-replace="true">
</span>
<br />
<button type="submit">
Submit</button>
名称</label>
<input id="name" name="name" data-val="true" data-val-required="是不是忘记输入名称了?" type="text"
value="" />
<span class="field-validation-valid" data-valmsg-for="name" data-valmsg-replace="true">
</span>
<label for="text">
年龄</label>
<input id="age" name="age" type="text" data-val="true" data-val-required="年龄也是必须输入的哦!"
value="" />
<span class="field-validation-valid" data-valmsg-for="age" data-valmsg-replace="true">
</span>
<br />
<button type="submit">
Submit</button>
增加js,这段js是将服务返回的错误消息进行显示
$.validator.addMethod("failure", function () { return false; });
$.validator.unobtrusive.adapters.addBool("failure");
$.validator.unobtrusive.revalidate = function (form, validationResult) {
$.removeData(form[0], 'validator');
var serverValidationErrors = [];
for (var property in validationResult) {
var elementId = property.toLowerCase();
elementId = elementId.substr(elementId.indexOf('.') + 1);
var item = form.find('#' + elementId);
serverValidationErrors.push(item);
item.attr('data-val-failure', validationResult[property][0]);
jQuery.validator.unobtrusive.parseElement(item[0]);
}
form.valid();
$.removeData(form[0], 'validator');
$.each(serverValidationErrors, function () {
this.removeAttr('data-val-failure');
jQuery.validator.unobtrusive.parseElement(this[0]);
});
}
$.validator.unobtrusive.adapters.addBool("failure");
$.validator.unobtrusive.revalidate = function (form, validationResult) {
$.removeData(form[0], 'validator');
var serverValidationErrors = [];
for (var property in validationResult) {
var elementId = property.toLowerCase();
elementId = elementId.substr(elementId.indexOf('.') + 1);
var item = form.find('#' + elementId);
serverValidationErrors.push(item);
item.attr('data-val-failure', validationResult[property][0]);
jQuery.validator.unobtrusive.parseElement(item[0]);
}
form.valid();
$.removeData(form[0], 'validator');
$.each(serverValidationErrors, function () {
this.removeAttr('data-val-failure');
jQuery.validator.unobtrusive.parseElement(this[0]);
});
}
增加服务器返回错误消息显示操作
400 /* BadRequest */: function (jqxhr) {
var validationResult = $.parseJSON(jqxhr.responseText);
$.validator.unobtrusive.revalidate(form, validationResult.ModelState);
}
var validationResult = $.parseJSON(jqxhr.responseText);
$.validator.unobtrusive.revalidate(form, validationResult.ModelState);
}
浏览测试得到效果
1 没有任何输入
2 输入不合法