webapi中的模型验证
生活随笔
收集整理的這篇文章主要介紹了
webapi中的模型验证
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
mic: https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api
webapi中推薦我們使用Dto來創建接受實體和輸出實體,對于有些傳入/請求的參數是有限制的,非空,電話等等,我們可以統一進行處理這些。
需要了解:
webapi接受json參數:webapi 獲取json數據
數據注解:Code First 二 DataAnnotation 數據注解
?
流程:我們需要使用方法過濾器在每次執行方法之前進行驗證,處理驗證結果。我們Dto需要使用數據注解來標識
單個方法驗證:
[HttpPost]
public async Task<IHttpActionResult> VerifyAsync(TestInDto inDto){ if (ModelState.IsValid){return await Task.FromResult(Ok(inDto));}else{List<KeyValuePair<string, ModelState>> vs = ModelState.ToList();List<object> obj = new List<object>();foreach (KeyValuePair<string, ModelState> item in vs){IList<string> strList = new List<string>();foreach (var err in item.Value.Errors){strList.Add(err.ErrorMessage);}obj.Add(new{key = item.Key.Split('.')[1],errorMessage = strList});}return await Task.FromResult(Ok(new { errcode=-1,err=obj}));}} public class TestInDto{/// <summary>/// id/// </summary>public int? Id { get; set; }/// <summary>/// /// </summary>[Required(ErrorMessage ="名字不能為空")][StringLength(maximumLength:50,ErrorMessage ="最大長度不能超過50")]public string Name { get; set; }}
?
使用方法過濾器:
①創建自己的方法過濾器
public class MyActionFilterAttribute : ActionFilterAttribute{public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken){if (!actionContext.ModelState.IsValid){List<KeyValuePair<string, ModelState>> vs = actionContext.ModelState.ToList();List<object> objList = new List<object>();foreach (KeyValuePair<string, ModelState> item in vs){IList<string> strList = new List<string>();foreach (ModelError err in item.Value.Errors){strList.Add(err.ErrorMessage);}objList.Add(new{key = item.Key.Split('.')[1],errorMessage = strList});}var obj = new{errcode = -1,err = objList};actionContext.Response = new HttpResponseMessage(){Content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json")};}return base.OnActionExecutingAsync(actionContext, cancellationToken);}?
②使用
針對單個方法:在方法上面使用特性來標識,也可以在控制器上面
?
?全局:Global.asax?全球文件中添加
?
結果:
?
轉載于:https://www.cnblogs.com/Sea1ee/p/10490006.html
總結
以上是生活随笔為你收集整理的webapi中的模型验证的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CSS 垂直居中
- 下一篇: [Swift]LeetCode673.