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 前言 前面的几个篇幅主要围绕控制器的执行过程,奈何执行过程中包含的知识点太庞大了,只能一部分一部分的去讲解,在上两篇中我们看到在 ...
随机推荐
- java -日期处理
1. 计算某年某月份 总有多少个周,每周的开始和结束时间? 思路:1.计算出本月实际的总天数 2.循环每一天,判断这天是否是 周日(1),如果是,周数加1,再次判断是否是月的第一个周一,如是,开始时间 ...
- infragistics-webdatagrid
infragistics-webdatagrid DataRow DataTable DataSet DataColumn stringBuilder append appendFormat 存储过程 ...
- 【转】精选30个优秀的CSS技术和实例
今天,我为大家收集精选了30个使用纯CSS完成的强大实践的优秀CSS技术和实例,您将在这里发现很多与众不同的技术,比如:图片集.阴影效果.可扩展按钮.菜单等-这些实例都是使用纯CSS和HTML实现的. ...
- 面试题目——《CC150》排序与查找
面试题11.1:给定两个排序后的数组A和B,其中A的末端有足够的缓冲空间容纳B.编写一个方法,将B合并入A并排序. package cc150.sort_search; public class Me ...
- php中session锁--如何防止阻塞请求(译)
现代浏览器限制到一个host并发连接的数量一般为4或6.这意味着,如果您的web页面加载几十个来自同一个host的assert file(js.图像.css)时,由于并发数的限制,会产生排队.同样甚至 ...
- Spring系列之Spring常用注解总结
传统的Spring做法是使用.xml文件来对bean进行注入或者是配置aop.事物,这么做有两个缺点:1.如果所有的内容都配置在.xml文件中,那么.xml文件将会十分庞大:如果按需求分开.xml文件 ...
- jsp页面中引用其他页面的方法
初看这个标题....大家的感觉一定是好2啊.....博主一定要说jsp的动态引用(jsp:include)和静态引用(@include)了.介绍这两者区别的文章已经烂大街了..一搜一大把..博主竟然还 ...
- linux下实现在程序运行时的函数替换(热补丁)
声明:以下的代码成果,是参考了网上的injso技术,在本文的最后会给出地址,同时非常感谢injso技术原作者的分享. 但是injso文章中的代码存在一些问题,所以后面出现的代码是经过作者修改和检测的. ...
- 数位dp模板
#include <bits/stdc++.h> typedef long long LL; const int MOD = (int)1e9 + 7; LL L,R,G,T; int d ...
- PHP获取当前域名$_SERVER['HTTP_HOST']和$_SERVER['SERVER_NAME']的区别
开发站群软件,用到了根据访问域名判断子站点的相关问题,PHP获取当前域名有两个变量 $_SERVER['HTTP_HOST'] 和 $_SERVER['SERVER_NAME'],两者的区别以及哪个更 ...