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. js下载浏览器中的图片

    jquery function download(src) { var $a = $("<a></a>").attr("href", s ...

  2. 盒子模型简单理解(box-sizing)

    普通解析: 概念图示和公式: html结构 <div class="num1"></div> 1.只写 width.height(写背景是为了区分) .nu ...

  3. 自定义cell自适应高度

    UITableView在许多App种被大量的应用着,呈现出现的效果也是多种多样的,不能局限于系统的一种样式,所以需要自定义cell 自定义cell呈现的内容也是多种多样的,内容有多有少,所以需要一种能 ...

  4. jenkins使用简记

    一.安装 jenkins有多种安装方式,可以使用内嵌的Servlet容器运行,也可以基于Apache运行,也可以安装成Linux或Windows服务. 1.使用 Servlet 容器运行 从官网下载 ...

  5. golang笔记——map

    通过 new 创建的引用类型对象是不完整创建,比如 map,它仅分配了字典类型本身所需的内存(指针包装),而没有分配键值存储内存,也没有初始化散列桶等内部属性,因此无法工作,如下代码就是错误的: p ...

  6. Excel 实用技巧之一

    1.在单元格内换行: Alt+Enter 2.合并其他单元格文字并换行: A1&char(10)&B1 3.Excel计算样本估算总体方差:STDEV/STDEVA(),分母为n-1. ...

  7. 清北学堂模拟赛day7 错排问题

    /* 考虑一下已经放回m本书的情况,已经有书的格子不要管他,考虑没有书的格子,不考虑错排有(n-m)!种,在逐步考虑有放回原来位置的情况,已经放出去和已经被占好的格子,不用考虑,剩下全都考虑,设t=x ...

  8. 将十六进制色值转换成Color

    在给Background赋值时,除了自带的Red,Blue,Black等,可以通过以下方法赋予其他颜色. 主要是将Hex转换成ARGB(A:alpha,表示透明度.R:Red.G:Green.B:Bl ...

  9. Linux/CentOS 服务安装/卸载,开机启动chkconfig命令详解|如何让MySQL、Apache开机启动?

    chkconfig chkconfig在命令行操作时会经常用到.它可以方便地设置和查询不同运行级上的系统服务.这个可要好好掌握,用熟练之后,就可以轻轻松松的管理好你的启动服务了. 注:谨记chkcon ...

  10. sql 获取一批指定范围且不重复的随机数

    declare @M int,@N int set @m=10 set @n=1 select top 10 cast(rand(checksum(newid()))*(@M-@N)+@n as in ...