1. 文章目的
隨著 WebApiClient 的不斷完善,越來越多開發者選擇WebApiClient替換原生的HttpClient,本文將介紹WebApiClient的接口參數輸入有效性驗證的新特性。
2.DataAnnotations介紹
在 asp.net mvc
服務端編程中,我們在創建模型的時候,使用System.ComponentModel.DataAnnotations相關的驗證特性,配合mvc框架,可以做前端和后端雙向輸入驗證的效果。
public class UserInfo{ [Required] [StringLength(10, MinimumLength = 1)] public string Account { get; set; } [Required] [StringLength(10, MinimumLength = 6)] public string Password { get; set; }}
以上的Required就是驗證特性, asp.net mvc 在模型綁定的時候,會進行驗證一遍,驗證結果放在控制器的ModelState屬性里面。當然System.ComponentModel.DataAnnotations并不是 asp.net mvc 特有的,而是基礎庫自帶的,也就是說任何框架下都是可以使用的。
3. 接口參數值的輸入驗證
Validator靜態類提ValidateObject相關的方法,用于驗證實例和實例的屬性值,WebApiClient使用Validator類來完成接口方法的參數值輸入驗證:
/// <summary>/// 提供參數值和參數的屬性值輸入合法性驗證/// </summary>static class ParameterValidator{ /// <summary> /// 類型的屬性否需要驗證緩存 /// </summary> private static readonly ConcurrentCache<Type, bool> cache = new ConcurrentCache<Type, bool>(); /// <summary> /// 返回是否需要進行屬性驗證 /// </summary> /// <param name="instance">實例</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> /// 驗證參數值輸入合法性 /// 驗證參數的屬性值輸入合法性 /// </summary> /// <param name="parameter">參數描述</param> /// <param name="validateProperty">是否驗證屬性值</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.接口參數的DataAnnotations聲明
4.1 聲明參數值的驗證
新聞熱點
疑難解答