一、模型验证的作用

在ASP.NET Web API中,我们可以使用 System.ComponentModel.DataAnnotations 命名空间中的属性为模型上的属性设置验证规则。

一个模型验证栗子

using System.ComponentModel.DataAnnotations;
namespace MyApi.Models
{
public class Product
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public decimal Price { get; set; }
[Range(, )]
public double Weight { get; set; }
}
}

  和ASP.NET MVC中中的模型验证十分相似,上边的验证规则是:Name属性不能为空,Weight必须在0与999之间。关于验证属性的用法可以参考.NET MVC的验证属性。

客户端(没有必须的Name):

    <form action="api/Product" method="post">
Id:<input type="text" name="Id" value="4" /><br />
Price:<input type="text" name="Price" value="1.99" /><br />
Weight:<input type="text" name="Weight" value="2.99" /><br />
<input type="submit" value="Submit" />
</form>

控制器代码:

public class ProductsController : ApiController
{
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);
}
}
}

当我们提交表格时,google中返回的内容如下

两个小问题:

“Under-Posting”:客户端提交的模型缺少字段,如果是[required]修饰的字段,ModelState不通过验证,如果是数字类型的,用0补充。

“Over-Posting”:客户端也可以发送更多的数据,JSON格式化器只是忽略此值(XML格式化程序也是如此)。

二 、WebApi中的处理验证错误

第一步  添加过滤器

验证失败时,Web API不会自动向客户端返回错误,这就需要控制器来做出适当的响应。我们可以创建action filter用于在Action执行之前检查模型状态。和MVC中的用法一样,代码显示了一个示例:

    public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
//返回第一个异常的错误消息
actionContext.Response = actionContext.Request.CreateResponse(
HttpStatusCode.InternalServerError,
new { code = , msg = actionContext.ModelState.Values.First().Errors.First().ErrorMessage });
}
}
}

如果模型验证失败,则此过滤器返回包含验证错误的HTTP响应,这样就不再执行Action了。

第二步  使用过滤器

  如果我们想在全局使用这种方案,我们可以设置一个全局的过滤器,在配置阶段把上边的过滤器添加到 HttpConfiguration.Filters 集合中。

public static class WebApiConfig
{
  public static void Register(HttpConfiguration config)
{
config.Filters.Add(new ValidateModelAttribute());
}
}

  如果不想使用全局过滤器,我们也可以把filter设置为各个Controller或Action的属性:

public class ProductsController : ApiController
{
[ValidateModel]
public HttpResponseMessage Post(Product product)
{
// ...
}
}

这里主要总结了WebApi中的模型验证,了解更多可查看官网

Web API中的模型验证的更多相关文章

  1. Web API中的模型验证Model Validation

    数据注释 在ASP.NET Web API中,您可以使用System.ComponentModel.DataAnnotations命名空间中的属性为模型上的属性设置验证规则. using System ...

  2. .Net Core3.0 WEB API 中使用FluentValidation验证,实现批量注入

    为什么要使用FluentValidation 1.在日常的开发中,需要验证参数的合理性,不紧前端需要验证传毒的参数,后端也需要验证参数 2.在领域模型中也应该验证,做好防御性的编程是一种好的习惯(其实 ...

  3. .net core web api 默认的模型验证

    转载自 https://www.codercto.com/a/45938.html

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

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

  5. .NET Core WEB API中接口参数的模型绑定的理解

    在.NET Core WEB API中参数的模型绑定方式有以下表格中的几种: 微软官方文档说明地址:https://docs.microsoft.com/zh-cn/aspnet/core/web-a ...

  6. ASP.NET Core Web API中带有刷新令牌的JWT身份验证流程

    ASP.NET Core Web API中带有刷新令牌的JWT身份验证流程 翻译自:地址 在今年年初,我整理了有关将JWT身份验证与ASP.NET Core Web API和Angular一起使用的详 ...

  7. 【ASP.NET Web API教程】6.2 ASP.NET Web API中的JSON和XML序列化

    谨以此文感谢关注此系列文章的园友!前段时间本以为此系列文章已没多少人关注,而不打算继续下去了.因为文章贴出来之后,看的人似乎不多,也很少有人对这些文章发表评论,而且几乎无人给予“推荐”.但前几天有人询 ...

  8. Asp.Net Web API 2第十三课——ASP.NET Web API中的JSON和XML序列化

    前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.html 本文描述ASP.NET W ...

  9. ASP.NET Web API中的JSON和XML序列化

    ASP.NET Web API中的JSON和XML序列化 前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok ...

随机推荐

  1. HDU4341-Gold miner-分组DP

    模拟黄金矿工这个游戏,给出每一个金子的位置和所需时间,计算在给定时间内最大收益. 刚看这道题以为金子的位置没什么用,直接DP就行,WA了一发终于明白如果金子和人共线的话只能按顺序抓. 这就是需要考虑先 ...

  2. 最简单的spring boot web项目

    搭建效果为: 直接在网页输入请求,在页面中显示一行文字:Hello,Spring Boot 与一般的wen项目不同的地方: 1.不需要配置web.xml 文件,但需要注解@SpringBootAppl ...

  3. crawlspider_房多多

    框架写起来代码是真的简洁多了,还有就是在requests爬取房多多的时候,无法爬取所有地区,而这个就不受影响 代码请查看码云 运行结果:

  4. vsftpd 安装与配置

    下载安装vsftpd服务,db4用来支持文件数据库yum install -y vsftpd db4-utils ftp 建立宿主用户 vsftpduseradd -s /sbin/nologin - ...

  5. JSON数组形式字符串转换为List<Map<String,String>>的几种方法

    package com.zkn.newlearn.json; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArr ...

  6. Hdoj 1007 Quoit Design 题解

    Problem Description Have you ever played quoit in a playground? Quoit is a game in which flat rings ...

  7. Codeforces | CF1033D 【Divisors】

    题目大意:给定\(n(1\leq n\leq500)\)个数\(a_1,a_2\cdots,a_n(1\leq a_i\leq2\cdot10^{18})\),每个数有\(3\sim5\)个因数,求\ ...

  8. Privoxy将Socks代理转化HTTP代理

    使用步骤 安装Privoxy sudo pacman -S privoxy # Arch Linux 创建配置文件 mkdir -p ~/.config/privoxy 向~/.config/priv ...

  9. CF747F Igor and Interesting Numbers

    我佛了,这CF居然没有官方题解. 题意:给定k,t,求第k小的16进制数,满足每个数码的出现次数不超过t. 解: 每个数都有个出现次数限制,搞不倒.一开始想到了排序hash数位DP,不过写了写觉得不胜 ...

  10. 判断JDK安装成功的方法

    JDK安装成功之后,主要是要写入环境变量