WebApiClient的接口輸入驗證方法
1. 文章目的
隨著 WebApiClient 的不斷完善,越來越多開發(fā)者選擇WebApiClient替換原生的HttpClient,本文將介紹WebApiClient的接口參數(shù)輸入有效性驗證的新特性。
2.DataAnnotations介紹
在 asp.net mvc
服務(wù)端編程中,我們在創(chuàng)建模型的時候,使用System.ComponentModel.DataAnnotations相關(guān)的驗證特性,配合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 在模型綁定的時候,會進行驗證一遍,驗證結(jié)果放在控制器的ModelState屬性里面。當然System.ComponentModel.DataAnnotations并不是 asp.net mvc 特有的,而是基礎(chǔ)庫自帶的,也就是說任何框架下都是可以使用的。
3. 接口參數(shù)值的輸入驗證
Validator靜態(tài)類提ValidateObject相關(guān)的方法,用于驗證實例和實例的屬性值,WebApiClient使用Validator類來完成接口方法的參數(shù)值輸入驗證:
/// <summary> /// 提供參數(shù)值和參數(shù)的屬性值輸入合法性驗證 /// </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> /// 驗證參數(shù)值輸入合法性 /// 驗證參數(shù)的屬性值輸入合法性 /// </summary> /// <param name="parameter">參數(shù)描述</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.接口參數(shù)的DataAnnotations聲明
4.1 聲明參數(shù)值的驗證
例如GetByIdAsync方法有個id的參數(shù),服務(wù)器要求必填且最大長度為10的字符串,我們可以使用Required, StringLength(10)特性修飾id這個參數(shù),在接口調(diào)用時,WebApiClient會對id值進行驗證,如果不通過則拋出ValidationException的異常。
// /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ù)值的屬性驗證
對于自定義的模型類型,只要在屬性里聲明了相關(guān)的DataAnnotations,WebApiClient就自動進行屬性的輸入驗證。
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);
當user參數(shù)不為null的情況,就會驗證它的Account和Password兩個屬性。
4.3 聲明參數(shù)值、參數(shù)的屬性值同時驗證
對于4.2的例子,如果我們希望user參數(shù)值也不能為null,可以如下聲明方法:
// 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ù)的屬性驗證
如果你的模型的屬性已聲明驗證特性,但不希望WebApiClient進行屬性值驗證,可以在創(chuàng)建接口實例的時候,在配置項里禁用屬性驗證:
var config = new HttpApiConfig { UseParameterPropertyValidate = false }; var client = HttpApiClient.Create<IUserApi>(config);
6. 結(jié)束語
博主為WebApiClient庫的作者,本文向讀者介紹了DataAnnotations驗證特性在WebApiCiient下的使用方法,歡迎大家給WebApiClient提建議。 也希望大家多多支持腳本之家。
相關(guān)文章
asp.net利用ashx文件實現(xiàn)文件的上傳功能
這篇文章主要介紹了asp.net利用ashx文件實現(xiàn)文件的上傳功能,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-11-11ASP.NET?MVC5網(wǎng)站開發(fā)之添加、刪除、重置密碼、修改密碼、列表瀏覽管理員篇2(六)
這篇文章主要為大家詳細介紹了ASP.NET?MVC5網(wǎng)站開發(fā)之添加、刪除、重置密碼、修改密碼、列表瀏覽,感興趣的小伙伴們可以參考一下2016-08-08asp.net core 集成swagger ui的原理解析
本文主要講解了如何對API進行分組,這里僅僅是舉了一個按照API功能進行分組的例子,其實在實際開發(fā)中,要按照何種方式分組,可以按照需求靈活定義,比如按照API版本進行分組2021-10-10asp net core 2.1中如何使用jwt(從原理到精通)
這篇文章主要給大家介紹了關(guān)于asp net core 2.1中如何使用jwt(從原理到精通)的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起看看吧2018-11-11ASP.NET中TextBox使用Ajax控件顯示日期不全的問題解決方法
這篇文章介紹了ASP.NET中TextBox使用Ajax控件顯示日期不全的問題解決方法,有需要的朋友可以參考一下2013-10-10