欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

前言

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

方法如下

安裝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)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。

相關(guān)文章

最新評論