ASP.NET WEB API 自定义模型校验过滤器
对外公开WEB接口时,对模型校验是常见的安全常识,常见的写法是在controller中判断ModelState.IsValid,以注册用户API为例。
Model:
public class RegisterCustomerModel
{
[Required(ErrorMessage = "姓名不能为空")]
[StringLength(,ErrorMessage = "姓名长度不能超过10个字")]
public string Name { get; set; } [Required(ErrorMessage = "电话不能为空")]
[RegularExpression(@"^1[34578]\d{9}$", ErrorMessage = "电话号码格式不正确")]
public string Phone { get; set; } [Required(ErrorMessage = "密码不能为空")]
[StringLength(, ErrorMessage = "密码长度不能超过48个字符")]
public string Password { get; set; } }
打印校验失败的错误消息代码:
public static class ModelStateExtension
{
public static string ToErrorMessage(this ModelStateDictionary modelStateDictionary)
{
var stringBuilder = new StringBuilder(); foreach (var value in modelStateDictionary.Values)
{
foreach (var error in value.Errors)
{
stringBuilder.AppendLine(error.ErrorMessage);
}
} return stringBuilder.ToString();
}
}
Controller:
public ResponseProtocol Register(RegisterCustomerModel registerCustomerModel)
{
if (!ModelState.IsValid)
{
return new ResponseProtocol((int)ResponseResultEnum.ValidateError, ModelState.ToErrorMessage(), string.Empty);
} Customer customer = new Customer
{
Name = registerCustomerModel.Name,
Phone = registerCustomerModel.Phone,
WeiXinNo = registerCustomerModel.WeiXinNo,
Company = registerCustomerModel.Company,
UpdateTime = DateTime.Now
}; _customerService.Add(customer); return new ResponseProtocol((int)ResponseResultEnum.Success, "注册成功", string.Empty);
}
以上写法是在controller里进行校验,缺点是每个需要进行校验的controller都要写一次,为了消除重复,可以将校验代码写入全局过滤器中,由过滤器进行统一模型校验,修改后的代码:
public class ValidationModelFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
//get方法不进行模型校验
if (actionContext.Request.Method.Method=="GET")
{
return;
} if (!actionContext.ModelState.IsValid)
{
var error = JsonConvert.SerializeObject(new ResponseProtocol()
{
Code =(int)ResponseResultEnum.ValidateError,
Message = actionContext.ModelState.ToErrorMessage(),
Data = string.Empty
}); var httpResponseMessage = new HttpResponseMessage
{
Content = new StringContent(error)
}; httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
actionContext.Response = httpResponseMessage;
}
}
}
然后在全局过滤器(WebApiConfig)注册一下: config.Filters.Add(new ValidationModelFilter());
ASP.NET WEB API 自定义模型校验过滤器的更多相关文章
- ASP.NET Web API 管道模型
ASP.NET Web API 管道模型 前言 ASP.NET Web API是一个独立的框架,也有着自己的一套消息处理管道,不管是在WebHost宿主环境还是在SelfHost宿主环境请求和响应都是 ...
- ASP.NET Web API 自定义MediaType实现jsonp跨域调用
代码来自<ASP.NET Web API 2 框架揭秘>一书. 直接上代码: /// <summary> /// 自定义jsonp MediaType /// </sum ...
- ASP.NET Web API编程——模型验证与绑定
1.模型验证 使用特性约束模型属性 可以使用System.ComponentModel.DataAnnotations提供的特性来限制模型. 例如,Required特性表示字段值不能为空,Range特 ...
- ASP.NET Web API 自定义 HttpParameterBinding
背景 问题的起因是这样的.群里面一个哥们儿发现在使用 ASP.NET WebAPI 时,不能在同一个方法签名中使用多次 FromBodyAttribute 这个 Attribute .正好我也在用 W ...
- ASP.NET Web API模型验证以及异常处理方式
ASP.NET Web API的模型验证与ASP.NET MVC一样,都使用System.ComponentModel.DataAnnotations. 具体来说,比如有:[Required(Erro ...
- Asp.Net Web API 2第七课——Web API异常处理
前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.html 本文主要来讲解Asp.Ne ...
- 【ASP.NET Web API教程】4.3 ASP.NET Web API中的异常处理
原文:[ASP.NET Web API教程]4.3 ASP.NET Web API中的异常处理 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本系列教程,请先看前面的内 ...
- Asp.Net Web API(四)
HttpResponseException-----HTTP响应异常 如果Web API控制器抛出一个未捕捉的异常,会发生什么呢?在默认情况下,大多数异常都会转换为一个带有状态码500的内部服务器错误 ...
- ASP.NET Web API 控制器创建过程(一)
ASP.NET Web API 控制器创建过程(一) 前言 在前面对管道.路由有了基础的了解过后,本篇将带大家一起学习一下在ASP.NET Web API中控制器的创建过程,这过程分为几个部分下面的内 ...
随机推荐
- springcloud(三):服务提供与调用
上一篇文章我们介绍了eureka服务注册中心的搭建,这篇文章介绍一下如何使用eureka服务注册中心,搭建一个简单的服务端注册服务,客户端去调用服务使用的案例. 案例中有三个角色:服务注册中心.服务提 ...
- Java IO详解(五)------包装流
File 类的介绍:http://www.cnblogs.com/ysocean/p/6851878.html Java IO 流的分类介绍:http://www.cnblogs.com/ysocea ...
- css文字溢出隐藏,及强制断句
只显示一行文字,便溢出隐藏 text-overflow: ellipsis; white-place: nowrap; overflow: hidden; 显示 n 行文字后便溢出隐藏 displa ...
- java swing 添加 jcheckbox复选框
总体上而言,Java Swing编程有两大特点:麻烦.效果差. 麻烦是说由于设计器的使用不方便(如果您希望使用窗体设计器通过快速拖拽控件建立您的Java Swing GUI程序,请您使用MyEclip ...
- 开涛spring3(12.1) - 零配置 之 12.1 概述
12.1 概述 12.1.1 什么是零配置 在SSH集成一章中大家注意到项目结构和包结构是不是很有规律,类库放到WEB-INF/lib文件夹下,jsp文件放到WEB-INF/jsp文件夹下,web ...
- TP框架 增删查
TP框架添加数据到数据库1.使用数组方式添加造模型对象 2.使用AR方式 强类型语言存在的方式 3.使用自动收集表单添加 :只能用POST方式,提交数据一个操作方法实现两个逻辑:A显示页面B得到数据 ...
- 机器学习:Python实现聚类算法(一)之AP算法
1.算法简介 AP(Affinity Propagation)通常被翻译为近邻传播算法或者亲和力传播算法,是在2007年的Science杂志上提出的一种新的聚类算法.AP算法的基本思想是将全部数据点都 ...
- dns劫持分析
最近在做dns解析,关注的重点在查询域名ns记录上,异常日志中捕获到一个域名,dig查询: 查询请求类型为ns,dig结果确只有一条A记录.处于好奇,查询类型改为a类型: 这个域名dig 查询A记录, ...
- More 3D Graphics (rgl) for Classification with Local Logistic Regression and Kernel Density Estimates (from The Elements of Statistical Learning)(转)
This post builds on a previous post, but can be read and understood independently. As part of my cou ...
- Linux下让一个程序开机自动启动
1.chkconfig但是要在脚本中满足一定的条件(/etc/init.d/)下存在相关服务 2.将启动的程序写入到/etc/rc.local 选择建议: /etc/rc.local可以作为开机启动程 ...