最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

.Net Web Api中利用FluentValidate進行參數(shù)驗證的方法

 更新時間:2018年07月05日 11:06:35   作者:CodeMiner  
最近在做Web API,用到了流式驗證,就簡單的說說這個流式驗證,下面這篇文章主要給大家介紹了關(guān)于.Net Web Api中利用FluentValidate進行參數(shù)驗證的相關(guān)資料,,需要的朋友可以參考借鑒,下面隨著小編來一起學習學習吧

前言

本文主要介紹了關(guān)于.Net Web Api用FluentValidate參數(shù)驗證的相關(guān)內(nèi)容,下面話不多說了,來一起看看詳細的介紹吧。

方法如下

安裝FluentValidate

在ASP.NET Web Api中請安裝 FluentValidation.WebApi版本

創(chuàng)建一個需要驗證的Model

 public class Product 
 {
  public string name { get; set; }
  public string des { get; set; }
  public string place { get; set; }
 }

配置FluentValidation,需要繼承AbstractValidator類,并添加對應(yīng)的驗證規(guī)則

 public class ProductValidator : AbstractValidator<Product>
 {
  public ProductValidator()
  {
   RuleFor(product => product.name).NotNull().NotEmpty();//name 字段不能為null,也不能為空字符串
  }
 }

在Config中配置 FluentValidation

在 WebApiConfig配置文件中添加

public static class WebApiConfig
{
 public static void Register(HttpConfiguration config)
 {
  // Web API routes
  ...
  FluentValidationModelValidatorProvider.Configure(config);
 }
}

驗證參數(shù)

需要在進入Controller之前進行驗證,如果有錯誤就返回,不再進入Controller,需要使用 ActionFilterAttribute

public class ValidateModelStateFilter : ActionFilterAttribute
{
 public override void OnActionExecuting(HttpActionContext actionContext)
 {
  if (!actionContext.ModelState.IsValid)
  {
   actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
  }
 }
}

如果要讓這個過濾器對所有的Controller都起作用,請在WebApiConfig中注冊

public static class WebApiConfig
{
 public static void Register(HttpConfiguration config)
 {
  // Web API configuration and services
  config.Filters.Add(new ValidateModelStateFilter());

  // Web API routes
  ...

FluentValidationModelValidatorProvider.Configure(config);
 }
}

如果指對某一個Controller起作用,可以在Controller注冊

[ValidateModelStateFilter]
public class ProductController : ApiController
{
 //具體的邏輯
}

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。

相關(guān)文章

最新評論

嫩江县| 榕江县| 磐安县| 当雄县| 商河县| 马尔康县| 阿拉善左旗| 越西县| 武功县| 叶城县| 松原市| 咸阳市| 郴州市| 洛南县| 扶绥县| 辽宁省| 黄石市| 金山区| 武功县| 固阳县| 峨山| 清流县| 昌平区| 丰原市| 英吉沙县| 桐乡市| 道孚县| 安吉县| 阳春市| 吉首市| 德昌县| 宁远县| 乌恰县| 长治县| 通州市| 建德市| 文登市| 阿坝| 新安县| 沾益县| 佛坪县|