例如GetByIdAsync方法有个id的参数,服务器要求必填且最大长度为10的字符串,我们可以使用Required, StringLength(10)特性修饰id这个参数,在接口调用时,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 声明参数值的属性验证
对于自定义的模型类型,只要在属性里声明了相关的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内容
[HttpPost("webapi/user/UpdateWithJson")]
ITask<UserInfo> UpdateWithJsonAsync(
[JsonContent("yyyy-MM-dd HH:mm:ss")] UserInfo user);
当user参数不为null的情况,就会验证它的Account和Password两个属性。
4.3 声明参数值、参数的属性值同时验证
对于4.2的例子,如果我们希望user参数值也不能为null,可以如下声明方法:
// POST webapi/user/UpdateWithJson
// Body {"Account":"laojiu","Password":"123456"}
// Return json或xml内容
[HttpPost("webapi/user/UpdateWithJson")]
ITask<UserInfo> UpdateWithJsonAsync(
[Required][JsonContent("yyyy-MM-dd HH:mm:ss")] UserInfo user);
5. 禁用参数的属性验证
如果你的模型的属性已声明验证特性,但不希望WebApiClient进行属性值验证,可以在创建接口实例的时候,在配置项里禁用属性验证:
var config = new HttpApiConfig
{
UseParameterPropertyValidate = false
};
var client = HttpApiClient.Create<IUserApi>(config);
6. 结束语
博主为WebApiClient库的作者,本文向读者介绍了DataAnnotations验证特性在WebApiCiient下的使用方法,欢迎大家给WebApiClient提建议。 也希望大家多多支持易采站长站。








