Web Api 模型验证

时间:2023-03-10 04:09:18
Web Api 模型验证

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类型出错信息

Web Api 模型验证

返回json格式数据

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