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 前言 前面的几个篇幅主要围绕控制器的执行过程,奈何执行过程中包含的知识点太庞大了,只能一部分一部分的去讲解,在上两篇中我们看到在 ...
随机推荐
- wpf 获取datagrid中模板中控件
//获取name为datagrid中第三列第一行模板的控件 FrameworkElement item = dataGrid.Columns[].GetCellContent(dataGrid.Ite ...
- php桥接设计模式
<?php //桥接模式 abstract class info{ protected $send=null; public function __construct($send){ $this ...
- epoll ET模式陷阱分析
0. 前言 这篇文章主要记录在使用epoll实现NIO接入时所遇到的问题. 1. epoll简介 epoll是Linux下提供的NIO,其主要有两种模式,ET(Edge trige)和LT(Level ...
- yaf学习资料
yaf学习资料 文档 鸟哥的官方文档 Yaf框架结合PHPUnit的集成测试 php yaf框架扩展实践六--单元测试.计划任务.第三方库等 php yaf框架扩展实践一--配置篇 yaf实战例子 y ...
- Android中如何控制元素的显示隐藏?
在Android程序中,有时需要程序开启时默认隐藏某个控件,当单击某个按钮时才触发显示控件的内容.比如在查询员工资料时,提交查询后再显示查询到的表格内容: Android中控制元素的隐藏参考以下代码. ...
- nyoj 218 Dinner(贪心专题)
Dinner 时间限制:100 ms | 内存限制:65535 KB 难度:1 描述 Little A is one member of ACM team. He had just won t ...
- Linux设置Memcached开机启动
Memcached开机启动方式 方法一: 在 /etc/rc.d/rc.local 文件中追加启动命令 /usr/local/memcached/bin/memcached -u root -d - ...
- (转载)phpcms v9两步实现专题栏目生成路径去掉html和special
相信很多人都知道,phpcms v9专题是不支持自定义URL的,生成的专题路径是以/HTML/special/开头的.那么如何实现专题栏目生成路径去掉html和special呢?通过修改程序的PHP源 ...
- 听说awk语言也可以编写脚本
导读 从 awk 系列开始,我们都是在命令行或者脚本文件里写一些简短的 awk 命令和程序.然而 awk 和 shell 一样也是一个解释型语言.通过从开始到现在的一系列的学习,你现在能写可以执行的 ...
- BZOJ 4582: [Usaco2016 Open]Diamond Collector
Descrirption 给你一个长度为 \(n\) 的序列,求将它分成两个序列后最多个数,每个序列最大值最小值不能超过 \(k\) Sol 二分+DP. 排一下序,找出以这个点结尾和开始的位置. 这 ...