1. 文章目的
隨著 WebApiClient 的不斷完善,越來(lái)越多開(kāi)發(fā)者選擇WebApiClient替換原生的HttpClient,本文將介紹WebApiClient的接口參數(shù)輸入有效性驗(yàn)證的新特性。
2.DataAnnotations介紹
在 asp.net mvc
服務(wù)端編程中,我們?cè)趧?chuàng)建模型的時(shí)候,使用System.ComponentModel.DataAnnotations相關(guān)的驗(yàn)證特性,配合mvc框架,可以做前端和后端雙向輸入驗(yàn)證的效果。
1
2
3
4
5
6
7
8
9
10
|
public class UserInfo { [Required] [StringLength(10, MinimumLength = 1)] public string Account { get ; set ; } [Required] [StringLength(10, MinimumLength = 6)] public string Password { get ; set ; } } |
以上的Required就是驗(yàn)證特性, asp.net mvc 在模型綁定的時(shí)候,會(huì)進(jìn)行驗(yàn)證一遍,驗(yàn)證結(jié)果放在控制器的ModelState屬性里面。當(dāng)然System.ComponentModel.DataAnnotations并不是 asp.net mvc 特有的,而是基礎(chǔ)庫(kù)自帶的,也就是說(shuō)任何框架下都是可以使用的。
3. 接口參數(shù)值的輸入驗(yàn)證
Validator靜態(tài)類(lèi)提ValidateObject相關(guān)的方法,用于驗(yàn)證實(shí)例和實(shí)例的屬性值,WebApiClient使用Validator類(lèi)來(lái)完成接口方法的參數(shù)值輸入驗(yàn)證:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
/// <summary> /// 提供參數(shù)值和參數(shù)的屬性值輸入合法性驗(yàn)證 /// </summary> static class ParameterValidator { /// <summary> /// 類(lèi)型的屬性否需要驗(yàn)證緩存 /// </summary> private static readonly ConcurrentCache<Type, bool > cache = new ConcurrentCache<Type, bool >(); /// <summary> /// 返回是否需要進(jìn)行屬性驗(yàn)證 /// </summary> /// <param name="instance">實(shí)例</param> /// <returns></returns> private static bool IsNeedValidateProperty( object instance) { if (instance == null ) { return false ; } var type = instance.GetType(); if (type == typeof ( string ) || type.GetTypeInfo().IsValueType == true ) { return false ; } return cache.GetOrAdd(type, t => t.GetProperties().Any(p => p.CanRead && p.IsDefined( typeof (ValidationAttribute), true ))); } /// <summary> /// 驗(yàn)證參數(shù)值輸入合法性 /// 驗(yàn)證參數(shù)的屬性值輸入合法性 /// </summary> /// <param name="parameter">參數(shù)描述</param> /// <param name="validateProperty">是否驗(yàn)證屬性值</param> /// <exception cref="ValidationException"></exception> public static void Validate(ApiParameterDescriptor parameter, bool validateProperty) { var name = parameter.Name; var instance = parameter.Value; foreach (var validation in parameter.ValidationAttributes) { validation.Validate(instance, name); } if (validateProperty == true && IsNeedValidateProperty(instance) == true ) { var ctx = new ValidationContext(instance) { MemberName = name }; Validator.ValidateObject(instance, ctx, true ); } } } |
4.接口參數(shù)的DataAnnotations聲明
4.1 聲明參數(shù)值的驗(yàn)證
例如GetByIdAsync方法有個(gè)id的參數(shù),服務(wù)器要求必填且最大長(zhǎng)度為10的字符串,我們可以使用Required, StringLength(10)特性修飾id這個(gè)參數(shù),在接口調(diào)用時(shí),WebApiClient會(huì)對(duì)id值進(jìn)行驗(yàn)證,如果不通過(guò)則拋出ValidationException的異常。
1
2
3
4
5
6
|
// /GET webapi/user/GetById?id=id001 // Return HttpResponseMessage [HttpGet( "webapi/user/GetById/{id}" )] [BasicAuth( "userName" , "password" )] ITask<HttpResponseMessage> GetByIdAsync( [Required, StringLength(10)] string id); |
4.2 聲明參數(shù)值的屬性驗(yàn)證
對(duì)于自定義的模型類(lèi)型,只要在屬性里聲明了相關(guān)的DataAnnotations,WebApiClient就自動(dòng)進(jìn)行屬性的輸入驗(yàn)證。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class UserInfo { [Required] [StringLength(10, MinimumLength = 1)] public string Account { get ; set ; } [Required] [StringLength(10, MinimumLength = 6)] public string Password { get ; set ; } } // POST webapi/user/UpdateWithJson // Body {"Account":"laojiu","Password":"123456"} // Return json或xml內(nèi)容 [HttpPost( "webapi/user/UpdateWithJson" )] ITask<UserInfo> UpdateWithJsonAsync( [JsonContent( "yyyy-MM-dd HH:mm:ss" )] UserInfo user); |
當(dāng)user參數(shù)不為null的情況,就會(huì)驗(yàn)證它的Account和Password兩個(gè)屬性。
4.3 聲明參數(shù)值、參數(shù)的屬性值同時(shí)驗(yàn)證
對(duì)于4.2的例子,如果我們希望user參數(shù)值也不能為null,可以如下聲明方法:
1
2
3
4
5
6
|
// POST webapi/user/UpdateWithJson // Body {"Account":"laojiu","Password":"123456"} // Return json或xml內(nèi)容 [HttpPost( "webapi/user/UpdateWithJson" )] ITask<UserInfo> UpdateWithJsonAsync( [Required][JsonContent( "yyyy-MM-dd HH:mm:ss" )] UserInfo user); |
5. 禁用參數(shù)的屬性驗(yàn)證
如果你的模型的屬性已聲明驗(yàn)證特性,但不希望WebApiClient進(jìn)行屬性值驗(yàn)證,可以在創(chuàng)建接口實(shí)例的時(shí)候,在配置項(xiàng)里禁用屬性驗(yàn)證:
1
2
3
4
5
|
var config = new HttpApiConfig { UseParameterPropertyValidate = false }; var client = HttpApiClient.Create<IUserApi>(config); |
6. 結(jié)束語(yǔ)
博主為WebApiClient庫(kù)的作者,本文向讀者介紹了DataAnnotations驗(yàn)證特性在WebApiCiient下的使用方法,歡迎大家給WebApiClient提建議。 也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.cnblogs.com/kewei/p/9406201.html