1.模型建立,在模型上类上添加System.ComponentModel.DataAnnotations验证属性

public class Product
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public decimal Price { get; set; }
[Range(0, 999)]
public double Weight { get; set; }
}

2.在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);
}
}

3.客户端调用并处理验证出错信息

 static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:57332/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // HTTP POST
var gizmo = new Product() { Name = "Gizmo", Price = 100, Weight = -200 };
HttpResponseMessage response = await client.PostAsJsonAsync("api/Product", gizmo); if (response.IsSuccessStatusCode)
{
// Get the URI of the created resource.
Uri gizmoUrl = response.Headers.Location;
Console.WriteLine("Post OK!");
}
else if (response.StatusCode == HttpStatusCode.BadRequest)
{
var x = await response.Content.ReadAsStringAsync();
Console.WriteLine(x); //输出出错信息 }
}
}

4.利用Filter Attribute来统一处理验证出错信息

建立Filter类

 public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(
HttpStatusCode.BadRequest, actionContext.ModelState);
}
}

在WebApiConfig.cs中添加如下代码

public static void Register(HttpConfiguration config)
{ config.Filters.Add(new ValidateModelAttribute()); //将这行代码添加进去
}

这样action中就可以直接写验证通过后的业务逻辑了,在每个action不需要单独使用 if (ModelState.IsValid)方法来判断了,代码变得简洁明了

 [ValidateModel]
public HttpResponseMessage Post(Product product)
{
// Do something with the product (not shown). return new HttpResponseMessage(HttpStatusCode.OK);
}

5.验证效果

响应信息

{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Pragma: no-cache
X-SourceFiles: =?UTF-8?B?ZDpcbXkgZG9jdW1lbnRzXHZpc3VhbCBzdHVkaW8gMjAxM1xQcm9qZWN0c1xNb2RlbFZhbGlkYXRpb25EZW1vXE1vZGVsVmFsaWRhdGlvbkRlbW9cYXBpXFByb2R1Y3Q=?=
Cache-Control: no-cache
Date: Thu, 07 Apr 2016 14:12:21 GMT
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Content-Length: 109
Content-Type: application/json; charset=utf-8
Expires: -1
}}

返回XML类型出错信息



返回json格式数据

{"Message":"请求无效。","ModelState":{"product.Weight":["字段 Weight 必须在 0 和 999 之间。"]}}

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

  1. ASP.NET Web API模型验证以及异常处理方式

    ASP.NET Web API的模型验证与ASP.NET MVC一样,都使用System.ComponentModel.DataAnnotations. 具体来说,比如有:[Required(Erro ...

  2. .net web api 权限验证

    做一个登录权限验证. 开始吧. using System; using System.Collections.Generic; using System.Drawing; using System.D ...

  3. .net core 中api 模型验证

    AddControllers/AddMvc方法允许添加自定义ActionFilterAttribute进行过滤 文档中这么定义Filter: 可以创建自定义筛选器,用于处理横切关注点. 横切关注点的示 ...

  4. ASP.NET Web API 安全验证之摘要(Digest)认证

    在基本认证的方式中,主要的安全问题来自于用户信息的明文传输,而在摘要认证中,主要通过一些手段避免了此问题,大大增加了安全性. 1.客户端匿名的方式请求 (无认证) HTTP/ Unauthorized ...

  5. Web API 身份验证 不记名令牌验证 Bearer Token Authentication

    1. Startup.Auth.cs文件 添加属性 public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; p ...

  6. ASP.NET Web API身份验证和授权

    英语原文地址:http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-a ...

  7. web api简单验证实现办法

    需要使用WEBAPI,但是有验证问题没解决.后来参考网上文章做了一下DEMO 思路: 就是根据用户的账号在服务端加密一个字符串,然后返回给用户端. 具体: 一个用户编号用于唯一身份识别,密码,一个密钥 ...

  8. ASP.NET MVC 5 WEB API 用户验证

    参考博客:ASP.NET MVC5+EF6+EasyUI 后台管理系统(65)-MVC WebApi 用户验证 (1) 参考博客:MVC WebApi 用户验证 (2)构建ASP.NET MVC5+E ...

  9. asp.net Web API 身份验证 不记名令牌验证 Bearer Token Authentication 简单实现

    1. Startup.Auth.cs文件 添加属性 1 public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; ...

随机推荐

  1. CentOS系统IPTables防火墙中FTP规则设置

    时间 2016-04-21 10:32:15  虫虫开源 原文  http://www.sijitao.net/2403.html 主题 iptablesFTP防火墙 在设置ftp通过iptables ...

  2. MySQL复制和集群

    一.复制配置 (A) 主从服务器相同版本的数据库 (B) 主服务器上复制使用的账户,具有相应的权限. (C) 修改主服务器的配置文件my.cnf,开启BINLOG,并设置server-id的值.重启后 ...

  3. Sicily 1444: Prime Path(BFS)

    题意为给出两个四位素数A.B,每次只能对A的某一位数字进行修改,使它成为另一个四位的素数,问最少经过多少操作,能使A变到B.可以直接进行BFS搜索 #include<bits/stdc++.h& ...

  4. bootstrap 布局(收藏/摘抄)

    bootstrap 12栅格 布局

  5. 通过ip查询对方位置

    我们这里使用的是baidumap的高精度IP定位API的接口,具体说明可以参考baidu提供的文档 使用前需要申请一个AK密钥类似于Kgcx......................xxl8w的样式 ...

  6. Mac Vim + ctags 实现多目录跳转

    set tags=tags; set autochdir :wq保存. 在源码根目录中输入ctags -R命令.后重启vim,打开src文件,就能使用Ctrl+] 或 g Ctrl+] 来实现跳转了. ...

  7. VS2013 密钥 – 所有版本

    Visual Studio Ultimate 2013 KEY(密钥):BWG7X-J98B3-W34RT-33B3R-JVYW9 Visual Studio Premium 2013 KEY(密钥) ...

  8. 更改WAS Profiles的概要文件的server1的SDK版本

    WebSphere只能使用IBM JDK 哦,不能使用sun的JDK哦.不过如果只是改jdk的版本的话可以参考如下步骤:(以集群为例,假设具有管理节点Dmgr01,应用概要AppSrv01) 1. 确 ...

  9. ember.js路由无效的解决思路

    进入今天的问题,就是route ember中就一个html,单页面程序(spa),所以页面的跳转,也可以叫做页面的路由,其实就是在这一个html中,不断的进行html的插入和删除了(个人理解) emb ...

  10. javascript export excel

    <input type="button" onclick="tableToExcel('tablename', 'name')" value=" ...