webapi中的模型验证
mic: https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api
webapi中推薦我們使用Dto來(lái)創(chuàng)建接受實(shí)體和輸出實(shí)體,對(duì)于有些傳入/請(qǐng)求的參數(shù)是有限制的,非空,電話等等,我們可以統(tǒng)一進(jìn)行處理這些。
需要了解:
webapi接受json參數(shù):webapi 獲取json數(shù)據(jù)
數(shù)據(jù)注解:Code First 二 DataAnnotation 數(shù)據(jù)注解
?
流程:我們需要使用方法過(guò)濾器在每次執(zhí)行方法之前進(jìn)行驗(yàn)證,處理驗(yàn)證結(jié)果。我們Dto需要使用數(shù)據(jù)注解來(lái)標(biāo)識(shí)
單個(gè)方法驗(yàn)證:
[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 ="最大長(zhǎng)度不能超過(guò)50")]public string Name { get; set; }}
?
使用方法過(guò)濾器:
①創(chuàng)建自己的方法過(guò)濾器
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);}?
②使用
針對(duì)單個(gè)方法:在方法上面使用特性來(lái)標(biāo)識(shí),也可以在控制器上面
?
?全局:Global.asax?全球文件中添加
?
結(jié)果:
?
轉(zhuǎn)載于:https://www.cnblogs.com/Sea1ee/p/10490006.html
總結(jié)
以上是生活随笔為你收集整理的webapi中的模型验证的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: CSS 垂直居中
- 下一篇: [Swift]LeetCode673.