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