Dependency-Injected Validation in Web API

后端 未结 6 1005
遥遥无期
遥遥无期 2021-02-04 09:05

In MVC, I can create a Model Validator which can take Dependencies. I normally use FluentValidation for this. This allows me to, for example, check on account registration tha

6条回答
  •  不要未来只要你来
    2021-02-04 09:46

    FluentValidation has had support for WebApi for quite sometime (not sure if your question dates before that): https://fluentvalidation.codeplex.com/discussions/533373

    Quoting from the thread:

    {
       GlobalConfiguration.Configuration.Services.Add(typeof(System.Web.Http.Validation.ModelValidatorProvider),
           new WebApiFluentValidationModelValidatorProvider()
           {
               AddImplicitRequiredValidator = false //we need this otherwise it invalidates all not passed fields(through json). btw do it if you need
           });
           FluentValidation.ValidatorOptions.ResourceProviderType = typeof(FluentValidationMessages); // if you have any related resource file (resx)
           FluentValidation.ValidatorOptions.CascadeMode = FluentValidation.CascadeMode.Continue; //if you need!
    

    I have been using it in WebApi2 project without any issues.

提交回复
热议问题