1.模型建立,在模型上類上添加System.ComponentModel.DataAnnotations驗證屬性 ~~~C public class Product { public int Id { get; set; } [Required] public string Name { get; ...
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 之間。"]}}