Model Validation in ASP.NET Web API
Model Validation in ASP.NET Web API
原文:http://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api
本文主要讲述Web API中使用标记来验证数据,以及出路验证错误。
1. 数据注解 Data Annotations
在Web API中,使用System.ComponentModel.DataAnnotations中的属性来添加验证规则。
例如:
using System.ComponentModel.DataAnnotations;
namespace WebApiPractice.Models
{
public class Product
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
[Range(0, 999)]
public double Weight { get; set; }
}
}
Required属性要求Name不能为空。Range属性要求Weight的值在0~999之间。
在Controller中验证:
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);
}
}
"Under-Posting": 当客户端发送的值缺少的时候,一般使用Nullable来解决,因为基础类型都有一个默认值,比如int(0),double(0),string("")。
[Required] public decimal? Price { get; set; }
"Over-Posting": 客户端发送了过多的数据。一般采用DTO避免这种情况。
2. 处理验证错误
Web API不会自动将验证错误返回给客户端。需要控制器的action检查模型状态并做适当地返回。
在控制器的action被调用之前,可以创建一个action过滤器来检查模型的状态。
代码如下:
using System.Net;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace WebApiPractice.Filters
{
//模型验证
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(
HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
}
如果验证失败,过滤器将会返回包含验证错误的HTTP响应。这种情况下,控制器的action不会被调用。
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
Date: Tue, 16 Jul 2013 21:02:29 GMT
Content-Length: 331
{
"Message": "The request is invalid.",
"ModelState": {
"product": [
"Required property 'Name' not found in JSON. Path '', line 1, position 17."
],
"product.Name": [
"The Name field is required."
],
"product.Weight": [
"The field Weight must be between 0 and 999."
]
}
}
可以将验证的过滤器应用在所有控制器,或者单个控制器,单个action:
config.Filters.Add(new ValidateModelAttribute());
[ValidateModel]
public HttpResponseMessage Post(Product product)
测试代码:
public void PostProduct()
{
HttpClient httpClient = new HttpClient();
Product p = new Product();
p.Id = 12;
p.Price = 100;
var t = httpClient.PostAsJsonAsync("http://localhost:60865/api/products", p);
t.Wait();
System.Diagnostics.Debug.WriteLine(t.Result);
Console.WriteLine(t.Result);
}
Model Validation in ASP.NET Web API的更多相关文章
- Model Validation in ASP.NET Web API By Mike Wasson|July 20, 2012 268 of 294 people found this helpful
using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using ...
- Exception Handling in ASP.NET Web API webapi异常处理
原文:http://www.asp.net/web-api/overview/error-handling/exception-handling This article describes erro ...
- Exception Handling in ASP.NET Web API
public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErr ...
- 【ASP.NET Web API教程】2.1 创建支持CRUD操作的Web API
原文 [ASP.NET Web API教程]2.1 创建支持CRUD操作的Web API 2.1 Creating a Web API that Supports CRUD Operations2.1 ...
- 【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教程】6 格式化与模型绑定
原文:[ASP.NET Web API教程]6 格式化与模型绑定 6 Formats and Model Binding 6 格式化与模型绑定 本文引自:http://www.asp.net/web- ...
- [转]Enabling CRUD Operations in ASP.NET Web API 1
本文转自:https://docs.microsoft.com/en-us/aspnet/web-api/overview/older-versions/creating-a-web-api-that ...
- Asp.Net Web API 2第十五课——Model Validation(模型验证)
前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.html 本文参考链接文章地址htt ...
- ASP.NET Web API Model-ModelMetadata
ASP.NET Web API Model-ModelMetadata 前言 前面的几个篇幅主要围绕控制器的执行过程,奈何执行过程中包含的知识点太庞大了,只能一部分一部分的去讲解,在上两篇中我们看到在 ...
随机推荐
- Google Map API V3开发(6) 代码
Google Map API V3开发(1) Google Map API V3开发(2) Google Map API V3开发(3) Google Map API V3开发(4) Google M ...
- 浅谈ARP协议以及应用
0. 前言 本章主要简单的介绍ARP的协议格式,主机如何发送和处理ARP报文,以及免费ARP. 1. ARP协议原理 ARP,全称Address Resolution Protocol,地址解析协议, ...
- PHP读写文件
一:读取文件 例1: $xml = ""; //打开文件 $f = fopen('http://app.eyuebus.com/Public/apk/version.xml', ' ...
- JUnit4 中@AfterClass @BeforeClass @after @before的区别对比
JUnit4使用Java5中的注解(annotation),以下是JUnit4常用的几个annotation: @Before:初始化方法 对于每一个测试方法都要执行一次(注意与BeforeCla ...
- Git 简明教程
其他Git资料: Git Community Book 中文版
- C和指针 第三章 四种作用域
代码块作用域: 任何位于一对花括号之间是一个代码块,代码块内声明的标识符具有代码块作用域,嵌套代码块内,内部变量会屏蔽外部相同标示的标示符,非嵌套代码块,不会同时处于活动状态所以不会屏蔽. int m ...
- 如何让自己的app尽量不被系统杀死
1. 在Service中重写下面的方法,这个方法有三个返回值, START_STICKY是service被kill掉后自动重写创建 @Override public int onStartComman ...
- Qml 写的弹出层控件
QML弹出窗口组件,灯箱效果.动画效果,可拖拽 核心思路:一个mask层,一个最顶层,都用rectangle,禁止事件穿透 使用 Popup { id: popup width: 200; heigh ...
- npm start 作用
在配置phonecat项目时需要运行npm start在本地配置一个服务器环境,npm start首先会安装一系列的必要程序,这些程序依赖package.json中的内容,package.json中的 ...
- Lua 基础
Lua 5.3 的中文手册, http://cloudwu.github.io/lua53doc 在线浏览 --第一部分 -- 两个横线开始单行的注释 --[[ 加上两个[和]表示 多行的注释. -- ...