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 之间。"]}}

最新文章

  1. Matlab的68个小常识
  2. POJ 2342 Label:树形dp
  3. 【学习总结】OS X , IOS , IOS SDK , XCode之间的关系
  4. Git权威指南 读笔(3)
  5. ==和equals()的用法
  6. Win10无法连接远程桌面提示“你的凭据不工作”的三个解决方法
  7. 蓝桥杯比赛javaB组练习《四平方和》
  8. Java <clinit> & <init>
  9. 【转】 awk 学习笔记
  10. iSlide——图标库、图示库的用法
  11. fileUpload(草稿)
  12. Confluence 6 结构(Schema )设置
  13. POJ3669解题报告(bfs)
  14. Java 集合补充
  15. GeSHi Documentation
  16. GeneXus学习笔记——入门篇
  17. 【13】MD5编码、Zlib压缩解压缩
  18. Python并行编程(二):基于线程的并行
  19. php写入和读取文件内容
  20. 搭建开源入侵检测系统Snort并实现与防火墙联动

热门文章

  1. Linux学习之四--Nginx
  2. pic
  3. BZOJ 2091: [Poi2010]The Minima Game
  4. docker swarm-mode
  5. JQ倒计时天时分秒
  6. maven中classpath路径(转)
  7. Java基础高级二(多线程)
  8. java 标签库(核心,xml,sql ,国际化,函数)
  9. android Acitivity之间的几种传值方式(^_^)
  10. UML大战需求分析——阅读笔记06