- 在接口開發過程中免不了要去驗證參數的合法性,模型驗證就是幫助我們去驗證參數的合法性,我們可以在需要驗證的model屬性上加上Data Annotations特性后就會自動幫我們在action前去驗證輸入數據的合法性。
1.定義一個Person類
public class PersonDto {
public string Name { get; set; } public string Phone { get; set; } public int Age { get; set; } }
Person類有三個屬性,姓名,電話,年紀。
2.創建一個接口並以Person作為input參數並且返回input對象
public PersonDto Demo(PersonDto input) { var str = string.Empty; PersonDto dto = new PersonDto { Name = input.Name, Age=input.Age, Phone=input.Phone, }; return dto; }
3.用postman來調用這個接口
很明顯我傳入的參數是不合法的,但是接口依舊執行了。 那怎么去驗證參數的合法性呢?在接口里面寫if嗎?這時候模型驗證就發揮作用啦。
4.修改之前的Person類,引入using System.ComponentModel.DataAnnotations;
public class PersonDto { [Required(ErrorMessage = "姓名不能為空"), MaxLength(10, ErrorMessage = "名字太長啦"), MinLength(0, ErrorMessage = "名字太短")] [ RegularExpression(@"^[\u4e00-\u9fa5]+$", ErrorMessage = "姓名必須是中文")] public string Name { get; set; } [Required(ErrorMessage = "手機號碼不能為空"), RegularExpression(@"^\+?\d{0,4}?[1][3-8]\d{9}$", ErrorMessage = "手機號碼格式錯誤")] public string Phone { get; set; } [Range(1, 1000, ErrorMessage = "年紀必須在0-99之間")] public int Age { get; set; } }
在次調用這個接口。
如果參數參數的不合法會直接400且會根據定義的提示去提示前端參數哪里不合法。但是很多小伙伴的返回值都是通用的,怎么把這些提示放到自己的通用返回值里面呢?
5.定義一個通用的返回值
public class ResponseDto {/// <summary> /// 詳細錯誤信息 /// </summary> public string message { get; set; } /// <summary> /// 具體業務參數 /// </summary> public object data { get; set; } }
6.定義一個CustomResultFilter
public class CustomResultFilter : ActionFilterAttribute { public override void OnResultExecuting(ResultExecutingContext context) { if (!context.ModelState.IsValid) { ResponseDto result = new ResponseDto(); foreach (var item in context.ModelState.Values) { foreach (var error in item.Errors) { result.message += error.ErrorMessage + ","; result.data = "{}"; } } result.message = result.message.TrimEnd(','); context.Result = new JsonResult(result); } else { var result = context.Result as ObjectResult ?? null; context.Result = new OkObjectResult(new ResponseDto { message = "成功", data = result == null ? "{}" : result.Value }); base.OnResultExecuting(context); } } public override void OnActionExecuting(ActionExecutingContext context) { }
使用ModelState.IsValid來判斷模型驗證是否通過。
7.配置過濾器
public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { options.Filters.Add(typeof(CustomResultFilter)); }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new Info { Title = " API", Version = "v1", Description = "RESTful API", TermsOfService = " Service", Contact = new Contact { Name = "", Email = "", Url = "" } }); }); }
8.測試
模型驗證通過