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的更多相关文章

  1. 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 ...

  2. Exception Handling in ASP.NET Web API webapi异常处理

    原文:http://www.asp.net/web-api/overview/error-handling/exception-handling This article describes erro ...

  3. Exception Handling in ASP.NET Web API

    public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErr ...

  4. 【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 ...

  5. 【ASP.NET Web API教程】4.3 ASP.NET Web API中的异常处理

    原文:[ASP.NET Web API教程]4.3 ASP.NET Web API中的异常处理 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本系列教程,请先看前面的内 ...

  6. 【ASP.NET Web API教程】6 格式化与模型绑定

    原文:[ASP.NET Web API教程]6 格式化与模型绑定 6 Formats and Model Binding 6 格式化与模型绑定 本文引自:http://www.asp.net/web- ...

  7. [转]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 ...

  8. Asp.Net Web API 2第十五课——Model Validation(模型验证)

    前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.html 本文参考链接文章地址htt ...

  9. ASP.NET Web API Model-ModelMetadata

    ASP.NET Web API Model-ModelMetadata 前言 前面的几个篇幅主要围绕控制器的执行过程,奈何执行过程中包含的知识点太庞大了,只能一部分一部分的去讲解,在上两篇中我们看到在 ...

随机推荐

  1. iOS 关于修饰代理用weak还是assign

    对于weak:指明该对象并不负责保持delegate这个对象,delegate这个对象的销毁由外部控制. 对于strong:该对象强引用delegate,外界不能销毁delegate对象,会导致循环引 ...

  2. [Recommendation System] 推荐系统之协同过滤(CF)算法详解和实现

    1 集体智慧和协同过滤 1.1 什么是集体智慧(社会计算)? 集体智慧 (Collective Intelligence) 并不是 Web2.0 时代特有的,只是在 Web2.0 时代,大家在 Web ...

  3. UVA-11991 Easy Problem from Rujia Liu?

    Problem E Easy Problem from Rujia Liu? Though Rujia Liu usually sets hard problems for contests (for ...

  4. java 环境变量java_home配置多加了 \ 导致zookeeper莫名其妙问题。

    平时开发其实不太用得到java_home.path.classpath之类的环境变量,但是在命令行下运行java则需要用上,所以配错就可能出现莫名其妙错误. 错误JAVA_HOME 配置:D:\Pro ...

  5. JavaScript正则表达式详解(二)JavaScript中正则表达式函数详解

    二.JavaScript中正则表达式函数详解(exec, test, match, replace, search, split) 1.使用正则表达式的方法去匹配查找字符串 1.1. exec方法详解 ...

  6. PHP通用的XSS攻击过滤函数,Discuz系统中 防止XSS漏洞攻击,过滤HTML危险标签属性的PHP函数

    XSS攻击在最近很是流行,往往在某段代码里一不小心就会被人放上XSS攻击的代码,看到国外有人写上了函数,咱也偷偷懒,悄悄的贴上来... 原文如下: The goal of this function ...

  7. 最大堆 最小堆 解决TOPK问题

    堆:实质是一颗完全二叉树,最大堆的特点:父节点值均大于子节点:最小堆的父节点值均小于子节点: 一般使用连续内存存储堆内的值,因而可以根据当前节点的索引值推断子节点的索引值: 节点i的父节点为(i-1) ...

  8. angular自己最近学的一种筛选方法

    投资状态vm.statusList = [ {name:"项目状态",value:-1}, {name:"上线",value:0}, {name:"投 ...

  9. 群体结构图形三剑客——PCA图

    重测序便宜了,群体的测序和分析也多了起来.群体结构分析,是重测序最常见的分析内容.群体结构分析应用十分广泛,首先其本身是群体进化关系分析里面最基础的分析内容,其次在进行GWAS分析的时候,本身也需要使 ...

  10. Json序列化与反序列化

    参考:http://www.cnblogs.com/caofangsheng/p/5687994.html#commentform 下载链接:http://download.csdn.net/deta ...