日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

webapi中的模型验证

發(fā)布時(shí)間:2025/3/20 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 webapi中的模型验证 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。