SharpGrip.FluentValidation.AutoValidation.Mvc 1.4.0

Prefix Reserved
dotnet add package SharpGrip.FluentValidation.AutoValidation.Mvc --version 1.4.0                
NuGet\Install-Package SharpGrip.FluentValidation.AutoValidation.Mvc -Version 1.4.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="SharpGrip.FluentValidation.AutoValidation.Mvc" Version="1.4.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add SharpGrip.FluentValidation.AutoValidation.Mvc --version 1.4.0                
#r "nuget: SharpGrip.FluentValidation.AutoValidation.Mvc, 1.4.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install SharpGrip.FluentValidation.AutoValidation.Mvc as a Cake Addin
#addin nuget:?package=SharpGrip.FluentValidation.AutoValidation.Mvc&version=1.4.0

// Install SharpGrip.FluentValidation.AutoValidation.Mvc as a Cake Tool
#tool nuget:?package=SharpGrip.FluentValidation.AutoValidation.Mvc&version=1.4.0                

SharpGrip FluentValidation AutoValidation

Builds

FluentValidation.AutoValidation [Build]

Quality Gate Status
Maintainability Rating
Reliability Rating
Security Rating
Coverage

Introduction

SharpGrip FluentValidation AutoValidation is an extension of the FluentValidation (v10+) library enabling automatic asynchronous validation in MVC controllers and minimal APIs (endpoints). The library FluentValidation.AspNetCore is no longer being maintained and is unsupported. As a result, support for automatic validation provided by this library is no longer available. This library re-introduces this functionality for MVC controllers and introduces automatic validation for minimal APIs (endpoints). It enables developers to easily implement automatic validation in their projects.

Installation

Register your validators with the Microsoft DI service container, for instructions on setting that up please see https://docs.fluentvalidation.net/en/latest/di.html.

MVC controllers NuGet

For MVC controllers reference NuGet package SharpGrip.FluentValidation.AutoValidation.Mvc (https://www.nuget.org/packages/SharpGrip.FluentValidation.AutoValidation.Mvc).

using SharpGrip.FluentValidation.AutoValidation.Mvc.Extensions;

builder.Services.AddFluentValidationAutoValidation();

Minimal APIs (endpoints) NuGet

For minimal APIs (endpoints) reference NuGet package SharpGrip.FluentValidation.AutoValidation.Endpoints (https://www.nuget.org/packages/SharpGrip.FluentValidation.AutoValidation.Endpoints).

Enabling minimal API (endpoint) automatic validation can be done on both route groups and routes.

using SharpGrip.FluentValidation.AutoValidation.Endpoints.Extensions;

builder.Services.AddFluentValidationAutoValidation();

var app = builder.Build();
var endpointGroup = app.MapGroup("/some-group").AddFluentValidationAutoValidation();
endpointGroup.MapPost("/", (SomeModel someModel) => $"Hello {someModel.Name}");

app.MapPost("/", (SomeOtherModel someOtherModel) => $"Hello again {someOtherModel.Name}").AddFluentValidationAutoValidation();

Configuration

MVC controllers

Property Default value Description
DisableBuiltInModelValidation false Disables the built-in .NET model (data annotations) validation.
ValidationStrategy ValidationStrategy.All Configures the validation strategy. Validation strategy ValidationStrategy.All enables asynchronous automatic validation on all controllers inheriting from ControllerBase. Validation strategy ValidationStrategy.Annotations enables asynchronous automatic validation on controllers inheriting from ControllerBase decorated (class or method) with a [FluentValidationAutoValidationAttribute] attribute.
EnableBodyBindingSourceAutomaticValidation true Enables asynchronous automatic validation for parameters bound from BindingSource.Body binding sources (typically parameters decorated with the [FromBody] attribute).
EnableFormBindingSourceAutomaticValidation false Enables asynchronous automatic validation for parameters bound from BindingSource.Form binding sources (typically parameters decorated with the [FromForm] attribute).
EnableQueryBindingSourceAutomaticValidation true Enables asynchronous automatic validation for parameters bound from BindingSource.Query binding sources (typically parameters decorated with the [FromQuery] attribute).
EnablePathBindingSourceAutomaticValidation false Enables asynchronous automatic validation for parameters bound from BindingSource.Path binding sources (typically parameters decorated with the [FromRoute] attribute).
EnableCustomBindingSourceAutomaticValidation false Enables asynchronous automatic validation for parameters bound from BindingSource.Custom binding sources.
using SharpGrip.FluentValidation.AutoValidation.Mvc.Extensions;

builder.Services.AddFluentValidationAutoValidation(configuration =>
{
    // Disable the built-in .NET model (data annotations) validation.
    configuration.DisableBuiltInModelValidation = true;

    // Only validate controllers decorated with the `FluentValidationAutoValidation` attribute.
    configuration.ValidationStrategy = ValidationStrategy.Annotation;

    // Enable validation for parameters bound from `BindingSource.Body` binding sources.
    configuration.EnableBodyBindingSourceAutomaticValidation = true;

    // Enable validation for parameters bound from `BindingSource.Form` binding sources.
    configuration.EnableFormBindingSourceAutomaticValidation = true;

    // Enable validation for parameters bound from `BindingSource.Query` binding sources.
    configuration.EnableQueryBindingSourceAutomaticValidation = true;

    // Enable validation for parameters bound from `BindingSource.Path` binding sources.
    configuration.EnablePathBindingSourceAutomaticValidation = true;

    // Enable validation for parameters bound from 'BindingSource.Custom' binding sources.
    configuration.EnableCustomBindingSourceAutomaticValidation = true;

    // Replace the default result factory with a custom implementation.
    configuration.OverrideDefaultResultFactoryWith<CustomResultFactory>();
});

public class CustomResultFactory : IFluentValidationAutoValidationResultFactory
{
    public IActionResult CreateActionResult(ActionExecutingContext context, ValidationProblemDetails? validationProblemDetails)
    {
        return new BadRequestObjectResult(new {Title = "Validation errors", ValidationErrors = validationProblemDetails?.Errors});
    }
}

Minimal APIs (endpoints)

using SharpGrip.FluentValidation.AutoValidation.Endpoints.Extensions;

builder.Services.AddFluentValidationAutoValidation(configuration =>
{
    // Replace the default result factory with a custom implementation.
    configuration.OverrideDefaultResultFactoryWith<CustomResultFactory>();
});

public class CustomResultFactory : IFluentValidationAutoValidationResultFactory
{
    public IResult CreateResult(EndpointFilterInvocationContext context, ValidationResult validationResult)
    {
        var validationProblemErrors = validationResult.ToValidationProblemErrors();

        return Results.ValidationProblem(validationProblemErrors, "Some details text.", "Some instance text.", (int) HttpStatusCode.BadRequest, "Some title.");
    }
}

Validation attributes

MVC controllers

Customizing automatic validation behavior is achievable through the use of attributes.

The [AutoValidateAlways] attribute can be applied to a controller parameter, compelling automatic validation to disregard the validation check for a valid binding source. This proves useful when the ApiBehaviorOptions.SuppressInferBindingSourcesForParameters option is enabled, and a custom model is used, with parameters bound from multiple binding sources.

The [AutoValidateNever] attribute can be placed on a controller class, controller method, or controller parameter, instructing automatic validation to be skipped.

Validation interceptors

Note: Using validation interceptors is considered to be an advanced feature and is not needed for most use cases.

Validation interceptors allow you to intercept and alter the validation process by either implementing the IGlobalValidationInterceptor interface in a custom class or by implementing the IValidatorInterceptor on a single validator. During the validation process both instances get resolved and called (if they are present) creating a mini pipeline of validation interceptors:

==> IValidatorInterceptor.BeforeValidation()
==> IGlobalValidationInterceptor.BeforeValidation()

Validation

==> IValidatorInterceptor.AfterValidation()
==> IGlobalValidationInterceptor.AfterValidation()

Both interfaces define a BeforeValidation and a AfterValidation method.

The BeforeValidation method gets called before validation and allows you to return a custom IValidationContext which gets passed to the validator. In case you return null the default IValidationContext will be passed to the validator.

The AfterValidation method gets called after validation and allows you to return a custom IValidationResult which gets passed to the IFluentValidationAutoValidationResultFactory. In case you return null the default IValidationResult will be passed to the IFluentValidationAutoValidationResultFactory.

MVC controllers

// Example of a global validation interceptor.
builder.Services.AddTransient<IGlobalValidationInterceptor, CustomGlobalValidationInterceptor>();

public class CustomGlobalValidationInterceptor : IGlobalValidationInterceptor
{
    public IValidationContext? BeforeValidation(ActionExecutingContext actionExecutingContext, IValidationContext validationContext)
    {
        // Return a custom `IValidationContext` or null.
        return null;
    }

    public ValidationResult? AfterValidation(ActionExecutingContext actionExecutingContext, IValidationContext validationContext)
    {
        // Return a custom `ValidationResult` or null.
        return null;
    }
}

// Example of a single validator interceptor.
private class TestValidator : AbstractValidator<TestModel>, IValidatorInterceptor
{
    public TestValidator()
    {
        RuleFor(x => x.Parameter1).Empty();
        RuleFor(x => x.Parameter2).Empty();
        RuleFor(x => x.Parameter3).Empty();
    }

    public IValidationContext? BeforeValidation(ActionExecutingContext actionExecutingContext, IValidationContext validationContext)
    {
        // Return a custom `IValidationContext` or null.
        return null;
    }

    public ValidationResult? AfterValidation(ActionExecutingContext actionExecutingContext, IValidationContext validationContext)
    {
        // Return a custom `ValidationResult` or null.
        return null;
    }
}

Minimal APIs (endpoints)

// Example of a global validation interceptor.
builder.Services.AddTransient<IGlobalValidationInterceptor, CustomGlobalValidationInterceptor>();

public class CustomGlobalValidationInterceptor : IValidationInterceptor
{
    public IValidationContext? BeforeValidation(EndpointFilterInvocationContext endpointFilterInvocationContext, IValidationContext validationContext)
    {
        // Return a custom `IValidationContext` or null.
        return null;
    }

    public ValidationResult? AfterValidation(EndpointFilterInvocationContext endpointFilterInvocationContext, IValidationContext validationContext)
    {
        // Return a custom `ValidationResult` or null.
        return null;
    }
}

// Example of a single validator interceptor.
private class TestValidator : AbstractValidator<TestModel>, IValidatorInterceptor
{
    public TestValidator()
    {
        RuleFor(x => x.Parameter1).Empty();
        RuleFor(x => x.Parameter2).Empty();
        RuleFor(x => x.Parameter3).Empty();
    }

    public IValidationContext? BeforeValidation(EndpointFilterInvocationContext endpointFilterInvocationContext, IValidationContext validationContext)
    {
        // Return a custom `IValidationContext` or null.
        return null;
    }

    public ValidationResult? AfterValidation(EndpointFilterInvocationContext endpointFilterInvocationContext, IValidationContext validationContext)
    {
        // Return a custom `ValidationResult` or null.
        return null;
    }
}
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp3.1 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (6)

Showing the top 5 NuGet packages that depend on SharpGrip.FluentValidation.AutoValidation.Mvc:

Package Downloads
Fluxera.Extensions.Hosting.Modules.AspNetCore.HttpApi

A module that enables HTTP APIs for ASP.NET Core.

Joy.AspNetCore.WebApi

Package Description

DDD.HTTP

易用、强大、高效且面向 HTTP 和领域驱动的一站式企业级开发基础设施,支持 AspnetCore WebAPI(MVC)/MiniAPI,提供 API 文档、API 多版本管理、跨域(CORS)、异常中间件、API 结果统一返回、API Key 授权、JWT等能力。

IFNK.ApiHelper

net core api 帮助类 Release Notes: 1.0.3 修改自动验证 Release Notes: 1.0.7 修改自动验证

Smartphatz.Core.API

Package Description

GitHub repositories (1)

Showing the top 1 popular GitHub repositories that depend on SharpGrip.FluentValidation.AutoValidation.Mvc:

Repository Stars
TanvirArjel/CleanArchitecture
This repository contains the implementation of domain-driven design and clear architecture in ASP.NET Core.
Version Downloads Last updated
1.4.0 582,418 12/17/2023
1.3.1 136,698 10/19/2023
1.3.0 40,995 10/9/2023
1.2.0 33,946 9/22/2023
1.1.0 21,657 9/6/2023
1.0.1 6,498 8/21/2023
1.0.0 2,887 8/19/2023
1.0.0-beta3 115 8/17/2023
1.0.0-beta2 119 8/16/2023
1.0.0-beta1 1,905 8/16/2023