ASP.NET Web API之FluentValidation驗證

來源:互聯網
上載者:User

標籤:asp.net fluentvalidation

最近在做Web API,用到了流式驗證,就簡單的說說這個流式驗證。

首先我們定義一個Filter,如下

 public class ValidateResponseFilterAttribute : ActionFilterAttribute    {        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)        {            if (!actionContext.ModelState.IsValid)            {                //actionContext.ModelState.Keys                actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);            }        }    }

重寫Action執行方法,如果請求model存在異常,則將500error返回給用戶端。

接下來我們要怎麼做,定義一個BaseController

[ValidateResponseFilter]    public class BaseController : ApiController    {        protected HttpResponseMessage CreateSystemErrorResponse(string errorMsg)        {            return Request.CreateResponse<object>(                   new                   {                       IsSuc = false,                       ErrorMsg = errorMsg                   });        }        protected HttpResponseMessage CreateErrorResponse(string responseCode, Type type = null, HttpStatusCode statusCode = HttpStatusCode.OK)        {            return Request.CreateResponse<object>(statusCode,                   new                   {                       IsSuc = false,                       ErrorMsg = MessageResHelper.GetMessage(type != null ? type.Name : this.GetType().Name, responseCode)                   });        }        protected HttpResponseMessage CreateSucResponse(string responseCode = "")        {            if (string.IsNullOrEmpty(responseCode))            {                return Request.CreateResponse<object>(new                   {                       IsSuc = true                   });            }            return Request.CreateResponse<object>(                   new                   {                       IsSuc = true,                       ErrorMsg = MessageResHelper.GetMessage(this.GetType().Name, responseCode)                   });        }}

在BaseController上我們標記上面的Attribute,驗證不通過進行請求攔截。

接下來我們看一下Request的定義

public class CustomerValidateRequest : IValidatableObject{    private readonly IValidator _validator;    public CustomerValidateRequest()    {        _validator = new CustomerValidateRequestValidator();    }    public string Email { get; set; }    public string Password { get; set; }    public string ValidateCode { get; set; }    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)    {        return _validator.Validate(this).ToValidationResult();    }}

Request定義好之後,我們在最下面寫方法擷取驗證的結果。接下來再看看我們的Validator

public class CustomerValidateRequestValidator : AbstractValidator<CustomerValidateRequest>{    public CustomerValidateRequestValidator()    {        RuleFor(dto => dto.Email).NotNull().NotEmpty();        RuleFor(dto => dto.Password).NotNull().NotEmpty();        RuleFor(dto => dto.ValidateCode).NotNull().NotEmpty().Length(WebAppSettings.ValidateCodeLength);        When(dto => !string.IsNullOrWhiteSpace(dto.Email), () =>        {            RuleFor(c => c.Email).Matches(@"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");        });    }}

在這裡就是我們所要驗證的邏輯,可以驗證最基本的非空,長度,還可以驗證正則。這裡RuleFor返回的是如下的介面類型

public IRuleBuilderInitial<T, TProperty> RuleFor<TProperty>(Expression<Func<T, TProperty>> expression)

該介面繼承IRuleBuilder介面

public interface IRuleBuilderInitial<T, out TProperty> : IFluentInterface, IRuleBuilder<T, TProperty>, IConfigurable<PropertyRule, IRuleBuilderInitial<T, TProperty>>

IRuleBuild有很多擴充方法在DefaultValidatorExtensions類中,如下

650) this.width=650;" src="http://s4.51cto.com/wyfs02/M02/82/B5/wKiom1dex4vgC2RPAADiaPwWg-Q515.png" title="QQ20160613224249.png" alt="wKiom1dex4vgC2RPAADiaPwWg-Q515.png" />簡直是太多了,驗證信用卡,郵箱,比較大小,地區,不等於等等,當然你自己也可以擴充一些出來。

我們用Google DHC看一下效果

650) this.width=650;" src="http://s5.51cto.com/wyfs02/M00/82/B5/wKiom1deyIXRH6aMAAA64QyvxHc413.png" title="QQ20160613225136.png" alt="wKiom1deyIXRH6aMAAA64QyvxHc413.png" />

如果什麼都不傳,就會根據上面的驗證規則進行驗證。

650) this.width=650;" src="http://s4.51cto.com/wyfs02/M00/82/B4/wKioL1deye_wOztiAAA8hgpHD3A410.png" title="QQ20160613225255.png" alt="wKioL1deye_wOztiAAA8hgpHD3A410.png" />

如果傳了Email,則會驗證Email是否正確。

最後記得在Globle.asax.cs中增加如下代碼

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;ModelValidatorProviders.Providers.Add(new FluentValidationModelValidatorProvider(new AttributedValidatorFactory()));ValidatorOptions.CascadeMode = CascadeMode.StopOnFirstFailure;FluentValidationModelValidatorProvider.Configure();

好了,今天就到這裡,更多的內容請看下面這篇部落格。

https://chsakell.com/2015/01/17/web-api-powerful-custom-model-validation-with-fluentvalidation/

本文出自 “技術創造價值” 部落格,請務必保留此出處http://leelei.blog.51cto.com/856755/1788944

ASP.NET Web API之FluentValidation驗證

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.