Web API中的模型验证
一、模型验证的作用
在ASP.NET Web API中,我们可以使用 System.ComponentModel.DataAnnotations 命名空间中的属性为模型上的属性设置验证规则。
一个模型验证栗子
using System.ComponentModel.DataAnnotations;
namespace MyApi.Models
{
public class Product
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public decimal Price { get; set; }
[Range(, )]
public double Weight { get; set; }
}
}
和ASP.NET MVC中中的模型验证十分相似,上边的验证规则是:Name属性不能为空,Weight必须在0与999之间。关于验证属性的用法可以参考.NET MVC的验证属性。
客户端(没有必须的Name):
<form action="api/Product" method="post">
Id:<input type="text" name="Id" value="4" /><br />
Price:<input type="text" name="Price" value="1.99" /><br />
Weight:<input type="text" name="Weight" value="2.99" /><br />
<input type="submit" value="Submit" />
</form>
控制器代码:
public class ProductsController : ApiController
{
public HttpResponseMessage Post(Product product)
{
if (ModelState.IsValid)
{
// Do something with the product (not shown).
return new HttpResponseMessage(HttpStatusCode.OK);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
}
当我们提交表格时,google中返回的内容如下

两个小问题:
“Under-Posting”:客户端提交的模型缺少字段,如果是[required]修饰的字段,ModelState不通过验证,如果是数字类型的,用0补充。
“Over-Posting”:客户端也可以发送更多的数据,JSON格式化器只是忽略此值(XML格式化程序也是如此)。
二 、WebApi中的处理验证错误
第一步 添加过滤器
验证失败时,Web API不会自动向客户端返回错误,这就需要控制器来做出适当的响应。我们可以创建action filter用于在Action执行之前检查模型状态。和MVC中的用法一样,代码显示了一个示例:
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
//返回第一个异常的错误消息
actionContext.Response = actionContext.Request.CreateResponse(
HttpStatusCode.InternalServerError,
new { code = , msg = actionContext.ModelState.Values.First().Errors.First().ErrorMessage });
}
}
}
如果模型验证失败,则此过滤器返回包含验证错误的HTTP响应,这样就不再执行Action了。
第二步 使用过滤器
如果我们想在全局使用这种方案,我们可以设置一个全局的过滤器,在配置阶段把上边的过滤器添加到 HttpConfiguration.Filters 集合中。
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new ValidateModelAttribute());
}
}
如果不想使用全局过滤器,我们也可以把filter设置为各个Controller或Action的属性:
public class ProductsController : ApiController
{
[ValidateModel]
public HttpResponseMessage Post(Product product)
{
// ...
}
}
这里主要总结了WebApi中的模型验证,了解更多可查看官网。
Web API中的模型验证的更多相关文章
- Web API中的模型验证Model Validation
数据注释 在ASP.NET Web API中,您可以使用System.ComponentModel.DataAnnotations命名空间中的属性为模型上的属性设置验证规则. using System ...
- .Net Core3.0 WEB API 中使用FluentValidation验证,实现批量注入
为什么要使用FluentValidation 1.在日常的开发中,需要验证参数的合理性,不紧前端需要验证传毒的参数,后端也需要验证参数 2.在领域模型中也应该验证,做好防御性的编程是一种好的习惯(其实 ...
- .net core web api 默认的模型验证
转载自 https://www.codercto.com/a/45938.html
- 【ASP.NET Web API教程】4.3 ASP.NET Web API中的异常处理
原文:[ASP.NET Web API教程]4.3 ASP.NET Web API中的异常处理 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本系列教程,请先看前面的内 ...
- .NET Core WEB API中接口参数的模型绑定的理解
在.NET Core WEB API中参数的模型绑定方式有以下表格中的几种: 微软官方文档说明地址:https://docs.microsoft.com/zh-cn/aspnet/core/web-a ...
- ASP.NET Core Web API中带有刷新令牌的JWT身份验证流程
ASP.NET Core Web API中带有刷新令牌的JWT身份验证流程 翻译自:地址 在今年年初,我整理了有关将JWT身份验证与ASP.NET Core Web API和Angular一起使用的详 ...
- 【ASP.NET Web API教程】6.2 ASP.NET Web API中的JSON和XML序列化
谨以此文感谢关注此系列文章的园友!前段时间本以为此系列文章已没多少人关注,而不打算继续下去了.因为文章贴出来之后,看的人似乎不多,也很少有人对这些文章发表评论,而且几乎无人给予“推荐”.但前几天有人询 ...
- Asp.Net Web API 2第十三课——ASP.NET Web API中的JSON和XML序列化
前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.html 本文描述ASP.NET W ...
- ASP.NET Web API中的JSON和XML序列化
ASP.NET Web API中的JSON和XML序列化 前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok ...
随机推荐
- POJ 3020 -Antenna Placement-二分图匹配
题意:一个N*M的矩阵里有K个观测点,你必须放置天线覆盖所有观测点.每个雷达只能天线两个观测点,这两点必须相邻.计算最少天线数. 做法:将所有相邻的观测点连起来,建图.跑一遍匈牙利算法就计算出了最大的 ...
- python深度学习库keras——安装
TensorFlow安装keras需要在TensorFlow之上才能运行.所以这里安装TensorFlow.TensorFlow需要vs2015环境,需要wein64位环境,所以32位的小伙伴需要升级 ...
- Java异步、线程池解决方案
一.ThreadPoolExecutor------线程池 private static final ThreadPoolExecutor threadPoolExecutor = new Threa ...
- Alice's Chance POJ - 1698(按时间点建边)
Alice's Chance Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 7791 Accepted: 3174 De ...
- IDEA中Maven项目使用Junit4单元测试的写法
IDEA默认是安装了junit控件的,直接使用就好了 在maven项目的pom.xml文件中添加依赖 <dependency> <groupId>junit</group ...
- 【BZOJ5308】[ZJOI2018]胖(模拟,ST表,二分)
[BZOJ5308][ZJOI2018]胖(模拟,ST表,二分) 题面 BZOJ 洛谷 题解 首先发现每条\(0\)出发的边都一定会更新到底下的一段区间的点. 考虑存在一条\(0\rightarrow ...
- 【CF526G】Spiders Evil Plan(贪心)
[CF526G]Spiders Evil Plan(贪心) 题面 洛谷 CodeForces 给定一棵树,要求选择\(y\)条链,满足被链覆盖的所有点在树上联通,且\(x\)必定在联通块中. 对于每次 ...
- luogu3811 乘法逆元
逆元定义:若a*x=1(mod p),(a,p互质),则x为a mod p意义下的逆元 做法见https://www.luogu.org/blog/zjp-shadow/cheng-fa-ni-yua ...
- 20165223 学习基础和C语言基础调查
一.学习基础 1. 我所擅长的技能 从小我就对新鲜事物抱有浓厚的兴趣,因此多年来培养了许多爱好,对感兴趣的诸如绘画方面的国画.油画.素描.漫画等:音乐方面的钢琴.吉他.架子鼓等:运动方面的滑板.溜冰. ...
- D: Starry的神奇魔法(矩阵快速幂)
题目链接:https://oj.ismdeep.com/contest/Problem?id=1284&pid=3 D: Starry的神奇魔法 Time Limit: 1 s Me ...