├── calzolari.png ├── src ├── Calzolari.Grpc.AspNetCore.Validation │ ├── IValidatorLocator.cs │ ├── Internal │ │ ├── ValidationRpcException.cs │ │ ├── Base64Serializer.cs │ │ ├── BinarySerializer.cs │ │ ├── MetadataExtensions.cs │ │ ├── ValidationFailureExtensions.cs │ │ ├── ServiceCollectionValidationProvider.cs │ │ ├── ValidatingAsyncStreamReader.cs │ │ ├── DefaultErrorMessageHandler.cs │ │ └── ValidationInterceptor.cs │ ├── InlineValidator.cs │ ├── IValidatorErrorMessageHandler.cs │ ├── GrpcServiceOptionsHelper.cs │ ├── Calzolari.Grpc.AspNetCore.Validation.csproj │ └── ServiceCollectionHelper.cs ├── Calzolari.Grpc.AspNetCore.Validation.SampleRpc │ ├── appsettings.Development.json │ ├── appsettings.json │ ├── Calzolari.Grpc.AspNetCore.Validation.SampleRpc.csproj │ ├── Protos │ │ └── greet.proto │ ├── Program.cs │ ├── Startup.cs │ └── Services │ │ └── GreeterService.cs ├── Calzolari.Grpc.Domain │ ├── ValidationTrailers.cs │ └── Calzolari.Grpc.Domain.csproj ├── Calzolari.Grpc.AspNetCore.Validation.sln.DotSettings ├── Calzolari.Grpc.Net.Client.Validation │ ├── Base64Serializer.cs │ ├── BinarySerializer.cs │ ├── RpcExceptionExtensions.cs │ └── Calzolari.Grpc.Net.Client.Validation.csproj ├── Calzolari.Grpc.AspNetCore.Validation.Test │ ├── WebApplicationFactoryHelper.cs │ ├── Calzolari.Grpc.AspNetCore.Validation.Test.csproj │ ├── ServiceCollectionHelperTest.cs │ └── Integration │ │ ├── InlineValidatorIntegrationTest.cs │ │ ├── CustomValidatorIntegrationTest.cs │ │ └── CustomMessageHandlerIntegrationTest.cs └── Calzolari.Grpc.AspNetCore.Validation.sln ├── .github └── workflows │ ├── build.yml │ └── dotnet.yml ├── license.txt ├── README.md └── .gitignore /calzolari.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnthonyGiretti/grpc-aspnetcore-validator/HEAD/calzolari.png -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation/IValidatorLocator.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | 3 | namespace Calzolari.Grpc.AspNetCore.Validation; 4 | 5 | public interface IValidatorLocator 6 | { 7 | bool TryGetValidator(out IValidator result) where TRequest : class; 8 | } -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation.SampleRpc/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Grpc": "Information", 7 | "Microsoft": "Information" 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation/Internal/ValidationRpcException.cs: -------------------------------------------------------------------------------- 1 | using Grpc.Core; 2 | namespace Calzolari.Grpc.AspNetCore.Validation.Internal; 3 | 4 | internal class ValidationRpcException : RpcException 5 | { 6 | public ValidationRpcException(Status status, Metadata trailers) : base(status, trailers) 7 | { 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation.SampleRpc/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Warning", 5 | "Microsoft.Hosting.Lifetime": "Information" 6 | } 7 | }, 8 | "AllowedHosts": "*", 9 | "Kestrel": { 10 | "EndpointDefaults": { 11 | "Protocols": "Http2" 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation/InlineValidator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using FluentValidation; 3 | 4 | namespace Calzolari.Grpc.AspNetCore.Validation; 5 | 6 | public class InlineValidator : AbstractValidator 7 | { 8 | public InlineValidator(Action> configureRules) 9 | { 10 | configureRules(this); 11 | } 12 | } -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation/IValidatorErrorMessageHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using FluentValidation.Results; 4 | 5 | namespace Calzolari.Grpc.AspNetCore.Validation; 6 | 7 | public interface IValidatorErrorMessageHandler 8 | { 9 | Task HandleAsync(IList failures); 10 | } -------------------------------------------------------------------------------- /src/Calzolari.Grpc.Domain/ValidationTrailers.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Calzolari.Grpc.Domain 4 | { 5 | [Serializable] 6 | public class ValidationTrailers 7 | { 8 | public string PropertyName { get; set; } 9 | 10 | public string ErrorMessage { get; set; } 11 | 12 | public string AttemptedValue { get; set; } 13 | } 14 | } -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: .NET Core 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: actions/checkout@v1 12 | - name: Setup .NET 6 13 | uses: actions/setup-dotnet@v1 14 | with: 15 | dotnet-version: 6.0 16 | - name: Build with dotnet 17 | working-directory: src 18 | run: dotnet build --configuration Release 19 | -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation.sln.DotSettings: -------------------------------------------------------------------------------- 1 | 2 | True -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation/GrpcServiceOptionsHelper.cs: -------------------------------------------------------------------------------- 1 | using Calzolari.Grpc.AspNetCore.Validation.Internal; 2 | using Grpc.AspNetCore.Server; 3 | 4 | namespace Calzolari.Grpc.AspNetCore.Validation; 5 | 6 | public static class GrpcServiceOptionsHelper 7 | { 8 | public static GrpcServiceOptions EnableMessageValidation(this GrpcServiceOptions options) 9 | { 10 | options.Interceptors.Add(); 11 | return options; 12 | } 13 | } -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation/Internal/Base64Serializer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | using System.Text.Json; 4 | 5 | namespace Calzolari.Grpc.AspNetCore.Validation.Internal; 6 | 7 | public static class Base64Serializer 8 | { 9 | public static string ToBase64(this object obj) 10 | { 11 | string json = JsonSerializer.Serialize(obj); 12 | 13 | byte[] bytes = Encoding.Default.GetBytes(json); 14 | 15 | return Convert.ToBase64String(bytes); 16 | } 17 | } -------------------------------------------------------------------------------- /src/Calzolari.Grpc.Net.Client.Validation/Base64Serializer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | using System.Text.Json; 4 | 5 | namespace Calzolari.Grpc.Net.Client.Validation 6 | { 7 | public static class Base64Serializer 8 | { 9 | public static T FromBase64(this string base64Text) 10 | { 11 | byte[] bytes = Convert.FromBase64String(base64Text); 12 | 13 | string json = Encoding.Default.GetString(bytes); 14 | 15 | return JsonSerializer.Deserialize(json); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /.github/workflows/dotnet.yml: -------------------------------------------------------------------------------- 1 | name: .NET 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | pull_request: 7 | branches: [ "master" ] 8 | 9 | jobs: 10 | build: 11 | 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - uses: actions/checkout@v3 16 | - name: Setup .NET 17 | uses: actions/setup-dotnet@v2 18 | with: 19 | dotnet-version: 6.0.x 20 | - name: Restore dependencies 21 | run: dotnet restore 22 | - name: Build 23 | run: dotnet build --no-restore 24 | - name: Test 25 | run: dotnet test --no-build --verbosity normal 26 | -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation/Internal/BinarySerializer.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Runtime.Serialization.Formatters.Binary; 3 | 4 | namespace Calzolari.Grpc.AspNetCore.Validation.Internal 5 | { 6 | internal static class BinarySerializer 7 | { 8 | public static byte[] ToBytes(this T objectToSerialize) 9 | { 10 | var formatter = new BinaryFormatter(); 11 | var mStream = new MemoryStream(); 12 | 13 | formatter.Serialize(mStream, objectToSerialize); 14 | 15 | return mStream.ToArray(); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Calzolari.Grpc.Net.Client.Validation/BinarySerializer.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Runtime.Serialization.Formatters.Binary; 3 | 4 | namespace Calzolari.Grpc.Net.Client.Validation 5 | { 6 | internal static class BinarySerializer 7 | { 8 | public static T FromBytes(this byte[] arrayOfBytes) where T : class 9 | { 10 | var stream = new MemoryStream(); 11 | var formatter = new BinaryFormatter(); 12 | 13 | stream.Write(arrayOfBytes, 0, arrayOfBytes.Length); 14 | stream.Position = 0; 15 | 16 | return formatter.Deserialize(stream) as T; 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation/Internal/MetadataExtensions.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation.Results; 2 | using Grpc.Core; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | 6 | namespace Calzolari.Grpc.AspNetCore.Validation.Internal; 7 | 8 | internal static class MetadataExtensions 9 | { 10 | public static Metadata ToValidationMetadata(this IList failures) 11 | { 12 | var metadata = new Metadata(); 13 | if (failures.Any()) 14 | { 15 | metadata.Add(new Metadata.Entry("validation-errors-text", failures.ToValidationTrailers().ToBase64())); 16 | } 17 | return metadata; 18 | } 19 | } -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation.SampleRpc/Calzolari.Grpc.AspNetCore.Validation.SampleRpc.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net9.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation/Internal/ValidationFailureExtensions.cs: -------------------------------------------------------------------------------- 1 | using Calzolari.Grpc.Domain; 2 | using FluentValidation.Results; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | 6 | namespace Calzolari.Grpc.AspNetCore.Validation.Internal; 7 | 8 | internal static class ValidationFailureExtensions 9 | { 10 | public static IEnumerable ToValidationTrailers(this IList failures) 11 | { 12 | return failures.Select(x => new ValidationTrailers { 13 | PropertyName = x.PropertyName, 14 | AttemptedValue = x.AttemptedValue?.ToString(), 15 | ErrorMessage = x.ErrorMessage 16 | }).ToList(); 17 | } 18 | } -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation/Internal/ServiceCollectionValidationProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using FluentValidation; 3 | using Microsoft.Extensions.DependencyInjection; 4 | 5 | namespace Calzolari.Grpc.AspNetCore.Validation.Internal; 6 | 7 | internal class ServiceCollectionValidationProvider : IValidatorLocator 8 | { 9 | private readonly IServiceProvider _provider; 10 | 11 | public ServiceCollectionValidationProvider(IServiceProvider provider) 12 | { 13 | _provider = provider; 14 | } 15 | 16 | public bool TryGetValidator(out IValidator result) where TRequest : class 17 | { 18 | return (result = _provider.GetService>()) != null; 19 | } 20 | } -------------------------------------------------------------------------------- /src/Calzolari.Grpc.Net.Client.Validation/RpcExceptionExtensions.cs: -------------------------------------------------------------------------------- 1 | using Calzolari.Grpc.Domain; 2 | using Grpc.Core; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | 6 | namespace Calzolari.Grpc.Net.Client.Validation 7 | { 8 | public static class RpcExceptionExtensions 9 | { 10 | public static IEnumerable GetValidationErrors(this RpcException exception) 11 | { 12 | var validationTrailer = exception.Trailers.FirstOrDefault(x => x.Key == "validation-errors-text"); 13 | 14 | if (validationTrailer != null) 15 | { 16 | return validationTrailer.Value.FromBase64>(); 17 | } 18 | return null; 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation.SampleRpc/Protos/greet.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | option csharp_namespace = "Calzolari.Grpc.AspNetCore.Validation.SampleRpc"; 4 | 5 | package Greet; 6 | 7 | // The greeting service definition. 8 | service Greeter { 9 | // Sends a greeting 10 | rpc SayHello (HelloRequest) returns (HelloReply); 11 | rpc SayHelloServerStreaming (HelloRequest) returns (stream HelloReply); 12 | rpc SayHelloClientStreaming (stream HelloRequest) returns (HelloReply); 13 | rpc SayHelloDuplexStreaming (stream HelloRequest) returns (stream HelloReply); 14 | } 15 | 16 | // The request message containing the user's name. 17 | message HelloRequest { 18 | string name = 1; 19 | } 20 | 21 | // The response message containing the greetings. 22 | message HelloReply { 23 | string message = 1; 24 | } 25 | -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation.SampleRpc/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.Extensions.Hosting; 3 | 4 | namespace Calzolari.Grpc.AspNetCore.Validation.SampleRpc 5 | { 6 | public class Program 7 | { 8 | public static void Main(string[] args) 9 | { 10 | CreateHostBuilder(args).Build().Run(); 11 | } 12 | 13 | // Additional configuration is required to successfully run gRPC on macOS. 14 | // For instructions on how to configure Kestrel and gRPC clients on macOS, visit https://go.microsoft.com/fwlink/?linkid=2099682 15 | public static IHostBuilder CreateHostBuilder(string[] args) 16 | { 17 | return Host.CreateDefaultBuilder(args) 18 | .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); }); 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation/Internal/ValidatingAsyncStreamReader.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using Grpc.Core; 5 | 6 | namespace Calzolari.Grpc.AspNetCore.Validation.Internal; 7 | 8 | internal class ValidatingAsyncStreamReader : IAsyncStreamReader 9 | { 10 | private readonly IAsyncStreamReader _innerReader; 11 | private readonly Func _validator; 12 | 13 | public ValidatingAsyncStreamReader(IAsyncStreamReader innerReader, Func validator) 14 | { 15 | _innerReader = innerReader; 16 | _validator = validator; 17 | } 18 | 19 | public async Task MoveNext(CancellationToken cancellationToken) 20 | { 21 | var success = await _innerReader.MoveNext(cancellationToken).ConfigureAwait(false); 22 | if (success) 23 | { 24 | await _validator.Invoke(Current).ConfigureAwait(false); 25 | } 26 | 27 | return success; 28 | } 29 | 30 | public TRequest Current => _innerReader.Current; 31 | } 32 | -------------------------------------------------------------------------------- /license.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 anthonygiretti 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation/Internal/DefaultErrorMessageHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using FluentValidation.Results; 6 | 7 | namespace Calzolari.Grpc.AspNetCore.Validation.Internal 8 | { 9 | internal class DefaultErrorMessageHandler : IValidatorErrorMessageHandler 10 | { 11 | public Task HandleAsync(IList failures) 12 | { 13 | var errors = failures 14 | .Select(GetErrorMessage) 15 | .ToList(); 16 | 17 | return Task.FromResult(string.Join("\n", errors)); 18 | } 19 | 20 | private string GetErrorMessage(ValidationFailure failure) 21 | { 22 | var message = new StringBuilder(); 23 | message.Append($"Property {failure.PropertyName} failed validation."); 24 | 25 | if (!string.IsNullOrEmpty(failure.ErrorCode)) 26 | message.Append($" Error code was: {failure.ErrorCode}"); 27 | 28 | if (!string.IsNullOrEmpty(failure.ErrorMessage)) 29 | message.Append($" Error was: {failure.ErrorMessage}"); 30 | 31 | return message.ToString(); 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation.Test/WebApplicationFactoryHelper.cs: -------------------------------------------------------------------------------- 1 | using System.Net.Http; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using Calzolari.Grpc.AspNetCore.Validation.SampleRpc; 5 | using Grpc.Net.Client; 6 | using Microsoft.AspNetCore.Mvc.Testing; 7 | 8 | namespace Calzolari.Grpc.AspNetCore.Validation.Test 9 | { 10 | public static class WebApplicationFactoryHelper 11 | { 12 | public static GrpcChannel CreateGrpcChannel(this WebApplicationFactory factory) 13 | { 14 | var client = factory.CreateDefaultClient(new ResponseVersionHandler()); 15 | return GrpcChannel.ForAddress(client.BaseAddress, new GrpcChannelOptions 16 | { 17 | HttpClient = client 18 | }); 19 | } 20 | 21 | private class ResponseVersionHandler : DelegatingHandler 22 | { 23 | protected override async Task SendAsync(HttpRequestMessage request, 24 | CancellationToken cancellationToken) 25 | { 26 | var response = await base.SendAsync(request, cancellationToken); 27 | response.Version = request.Version; 28 | 29 | return response; 30 | } 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation.Test/Calzolari.Grpc.AspNetCore.Validation.Test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net9.0 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | all 15 | runtime; build; native; contentfiles; analyzers; buildtransitive 16 | 17 | 18 | all 19 | runtime; build; native; contentfiles; analyzers; buildtransitive 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation.Test/ServiceCollectionHelperTest.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using Xunit; 4 | 5 | namespace Calzolari.Grpc.AspNetCore.Validation.Test 6 | { 7 | public class ServiceCollectionHelperTest 8 | { 9 | [Fact] 10 | public void RegisterValidatorTest() 11 | { 12 | // Given 13 | var services = new ServiceCollection(); 14 | 15 | // When 16 | services.AddValidator(); 17 | var provider = services.BuildServiceProvider(); 18 | 19 | // Then 20 | provider.GetRequiredService>(); 21 | } 22 | 23 | [Fact] 24 | public void RegisterValidatorsTest() 25 | { 26 | // Given 27 | var services = new ServiceCollection(); 28 | 29 | // When 30 | services.AddValidators(); 31 | var provider = services.BuildServiceProvider(); 32 | 33 | // Then 34 | provider.GetRequiredService>(); 35 | } 36 | } 37 | 38 | 39 | public class TestValidator : AbstractValidator 40 | { 41 | } 42 | 43 | public class TestMessage 44 | { 45 | public string Message { get; set; } 46 | } 47 | } -------------------------------------------------------------------------------- /src/Calzolari.Grpc.Domain/Calzolari.Grpc.Domain.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | license.txt 5 | Anthony Giretti 6 | Calzolari 7 | Domain objects used for validation errors. Useless in standalone. Standalone package utilized by Calzolari.Grpc.Net.Client.Validation and Calzolari.Grpc.AspNetCore.Validation, because same assembly is required for serializing / deserializing in bytes 8 | grpc;dotnet;validator;validation;request-validation; 9 | https://github.com/AnthonyGiretti/grpc-aspnetcore-validator 10 | https://github.com/AnthonyGiretti/grpc-aspnetcore-validator 11 | true 12 | 9.0.0 13 | 9.0.0 14 | calzolari.png 15 | 16 | 9.0.0 17 | net9.0;netstandard2.1 18 | 19 | 20 | 21 | 22 | True 23 | 24 | 25 | 26 | True 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation.SampleRpc/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.AspNetCore.Http; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Microsoft.Extensions.Hosting; 6 | 7 | namespace Calzolari.Grpc.AspNetCore.Validation.SampleRpc 8 | { 9 | public class Startup 10 | { 11 | // This method gets called by the runtime. Use this method to add services to the container. 12 | // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 13 | public void ConfigureServices(IServiceCollection services) 14 | { 15 | services.AddGrpc(options => options.EnableMessageValidation()); 16 | } 17 | 18 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 19 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 20 | { 21 | if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); 22 | 23 | app.UseRouting(); 24 | 25 | app.UseEndpoints(endpoints => 26 | { 27 | endpoints.MapGrpcService(); 28 | 29 | endpoints.MapGet("/", 30 | async context => 31 | { 32 | await context.Response.WriteAsync( 33 | "Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909"); 34 | }); 35 | }); 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /src/Calzolari.Grpc.Net.Client.Validation/Calzolari.Grpc.Net.Client.Validation.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | true 5 | 9.0.0 6 | Anthony Giretti 7 | Calzolari 8 | Calzolari.Grpc.Net.Client.Validation 9 | Validation errors reader, requires Calzolari.Grpc.AspNetCore.Validation server side 10 | https://github.com/AnthonyGiretti/grpc-aspnetcore-validator 11 | license.txt 12 | grpc;dotnet;validator;validation;request-validation; 13 | https://github.com/AnthonyGiretti/grpc-aspnetcore-validator 14 | calzolari.png 15 | 16 | 9.0.0 17 | 9.0.0 18 | net9.0;netstandard2.1 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | True 33 | 34 | 35 | 36 | True 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation.SampleRpc/Services/GreeterService.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using Grpc.Core; 4 | using Microsoft.Extensions.Logging; 5 | 6 | namespace Calzolari.Grpc.AspNetCore.Validation.SampleRpc 7 | { 8 | public class GreeterService : Greeter.GreeterBase 9 | { 10 | private readonly ILogger _logger; 11 | 12 | public GreeterService(ILogger logger) 13 | { 14 | _logger = logger; 15 | } 16 | 17 | public override Task SayHello(HelloRequest request, ServerCallContext context) 18 | { 19 | return Task.FromResult(new HelloReply 20 | { 21 | Message = "Hello " + request.Name 22 | }); 23 | } 24 | 25 | public override async Task SayHelloServerStreaming(HelloRequest request, IServerStreamWriter responseStream, ServerCallContext context) 26 | { 27 | await responseStream.WriteAsync(new HelloReply 28 | { 29 | Message = "Hello " + request.Name 30 | }); 31 | } 32 | 33 | public override async Task SayHelloClientStreaming(IAsyncStreamReader requestStream, ServerCallContext context) 34 | { 35 | var names = new List(); 36 | await foreach (var request in requestStream.ReadAllAsync()) 37 | { 38 | names.Add(request.Name); 39 | } 40 | 41 | return new HelloReply {Message = "Hello " + string.Join(", ", names)}; 42 | } 43 | 44 | public override async Task SayHelloDuplexStreaming(IAsyncStreamReader requestStream, IServerStreamWriter responseStream, 45 | ServerCallContext context) 46 | { 47 | await foreach (var request in requestStream.ReadAllAsync()) 48 | { 49 | await responseStream.WriteAsync(new HelloReply {Message = "Hello " + request.Name}); 50 | } 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation.Test/Integration/InlineValidatorIntegrationTest.cs: -------------------------------------------------------------------------------- 1 | using Calzolari.Grpc.AspNetCore.Validation.SampleRpc; 2 | using FluentValidation; 3 | using Grpc.Core; 4 | using Microsoft.AspNetCore.Mvc.Testing; 5 | using Microsoft.AspNetCore.TestHost; 6 | using System.Threading.Tasks; 7 | using Xunit; 8 | 9 | namespace Calzolari.Grpc.AspNetCore.Validation.Test.Integration 10 | { 11 | public class InlineValidatorIntegrationTest : IClassFixture> 12 | { 13 | public InlineValidatorIntegrationTest(WebApplicationFactory factory) 14 | { 15 | _factory = factory 16 | .WithWebHostBuilder(builder => builder.ConfigureTestServices(services => 17 | { 18 | services.AddInlineValidator(rules => 19 | { 20 | rules.RuleFor(r => r.Name).NotEmpty(); 21 | }); 22 | services.AddGrpcValidation(); 23 | })); 24 | } 25 | 26 | private readonly WebApplicationFactory _factory; 27 | 28 | [Fact] 29 | public async Task Should_ResponseMessage_When_MessageIsValid() 30 | { 31 | // Given 32 | var client = new Greeter.GreeterClient(_factory.CreateGrpcChannel()); 33 | 34 | // When 35 | await client.SayHelloAsync(new HelloRequest 36 | { 37 | Name = "Not Empty Name" 38 | }); 39 | 40 | // Then nothing happen. 41 | } 42 | 43 | [Fact] 44 | public async Task Should_ThrowInvalidArgument_When_NameOfMessageIsEmpty() 45 | { 46 | // Given 47 | var client = new Greeter.GreeterClient(_factory.CreateGrpcChannel()); 48 | 49 | // When 50 | async Task Action() 51 | { 52 | await client.SayHelloAsync(new HelloRequest {Name = string.Empty}); 53 | } 54 | 55 | // Then 56 | var rpcException = await Assert.ThrowsAsync(Action); 57 | Assert.Equal(StatusCode.InvalidArgument, rpcException.Status.StatusCode); 58 | } 59 | } 60 | } -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation.Test/Integration/CustomValidatorIntegrationTest.cs: -------------------------------------------------------------------------------- 1 | using Calzolari.Grpc.AspNetCore.Validation.SampleRpc; 2 | using FluentValidation; 3 | using Grpc.Core; 4 | using Microsoft.AspNetCore.Mvc.Testing; 5 | using Microsoft.AspNetCore.TestHost; 6 | using System.Threading.Tasks; 7 | using Xunit; 8 | 9 | namespace Calzolari.Grpc.AspNetCore.Validation.Test.Integration 10 | { 11 | public class CustomValidatorIntegrationTest : IClassFixture> 12 | { 13 | public CustomValidatorIntegrationTest(WebApplicationFactory factory) 14 | { 15 | _factory = factory 16 | .WithWebHostBuilder(builder => builder.ConfigureTestServices(services => 17 | { 18 | //services.AddValidator(); 19 | services.AddValidators(); 20 | services.AddGrpcValidation(); 21 | })); 22 | } 23 | 24 | private readonly WebApplicationFactory _factory; 25 | 26 | [Fact] 27 | public async Task Should_ResponseMessage_When_MessageIsValid() 28 | { 29 | // Given 30 | var client = new Greeter.GreeterClient(_factory.CreateGrpcChannel()); 31 | 32 | // When 33 | await client.SayHelloAsync(new HelloRequest 34 | { 35 | Name = "Not Empty Name" 36 | }); 37 | 38 | // Then nothing happen. 39 | } 40 | 41 | [Fact] 42 | public async Task Should_ThrowInvalidArgument_When_NameOfMessageIsEmpty() 43 | { 44 | // Given 45 | var client = new Greeter.GreeterClient(_factory.CreateGrpcChannel()); 46 | 47 | // When 48 | async Task Action() 49 | { 50 | await client.SayHelloAsync(new HelloRequest {Name = string.Empty}); 51 | } 52 | 53 | // Then 54 | var rpcException = await Assert.ThrowsAsync(Action); 55 | Assert.Equal(StatusCode.InvalidArgument, rpcException.Status.StatusCode); 56 | } 57 | 58 | public class HelloRequestValidator : AbstractValidator 59 | { 60 | public HelloRequestValidator() 61 | { 62 | RuleFor(request => request.Name).NotEmpty(); 63 | } 64 | } 65 | } 66 | } -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation/Calzolari.Grpc.AspNetCore.Validation.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | Calzolari.Grpc.AspNetCore.Validation 4 | 9.0.0 5 | Anthony Giretti 6 | grpc;dotnet;validator;validation;request-validation;aspnetcore 7 | true 8 | https://github.com/AnthonyGiretti/grpc-aspnetcore-validator 9 | net9.0 10 | bin\Debug\Calzolari.Grpc.AspNetCore.Validation.xml 11 | Calzolari 12 | Calzolari.Grpc.AspNetCore.Validation 13 | 9.0.0 14 | license.txt 15 | Request message validator for Grpc.AspNetCore 16 | https://github.com/AnthonyGiretti/grpc-aspnetcore-validator 17 | calzolari.png 18 | 19 | 9.0.0 20 | 21 | 22 | 23 | bin\Release\Calzolari.Grpc.AspNetCore.Validation.xml 24 | 25 | 26 | 27 | bin\Debug\Calzolari.Grpc.AspNetCore.Validation.xml 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | True 43 | 44 | 45 | 46 | True 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29519.181 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Items", "Items", "{A041C68C-F36B-4DCE-A8BA-0442A8121F62}" 7 | ProjectSection(SolutionItems) = preProject 8 | ..\calzolari.png = ..\calzolari.png 9 | ..\README.md = ..\README.md 10 | EndProjectSection 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Calzolari.Grpc.AspNetCore.Validation.Test", "Calzolari.Grpc.AspNetCore.Validation.Test\Calzolari.Grpc.AspNetCore.Validation.Test.csproj", "{EA02FF95-08F8-4D3D-A193-66A3949FCBF6}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Calzolari.Grpc.AspNetCore.Validation.SampleRpc", "Calzolari.Grpc.AspNetCore.Validation.SampleRpc\Calzolari.Grpc.AspNetCore.Validation.SampleRpc.csproj", "{1D0CDAA5-9CA7-4DFA-847E-35BD51AD492C}" 15 | EndProject 16 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Calzolari.Grpc.AspNetCore.Validation", "Calzolari.Grpc.AspNetCore.Validation\Calzolari.Grpc.AspNetCore.Validation.csproj", "{C61FFB41-CB51-477F-BED2-BDCDA3105038}" 17 | EndProject 18 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Calzolari.Grpc.Net.Client.Validation", "Calzolari.Grpc.Net.Client.Validation\Calzolari.Grpc.Net.Client.Validation.csproj", "{E7963BF5-5687-47BE-A8EF-687C48680354}" 19 | EndProject 20 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Calzolari.Grpc.Domain", "Calzolari.Grpc.Domain\Calzolari.Grpc.Domain.csproj", "{BD66C9CB-B1D3-4A13-80AD-F6A4A7D7AAAF}" 21 | EndProject 22 | Global 23 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 24 | Debug|Any CPU = Debug|Any CPU 25 | Release|Any CPU = Release|Any CPU 26 | EndGlobalSection 27 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 28 | {EA02FF95-08F8-4D3D-A193-66A3949FCBF6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {EA02FF95-08F8-4D3D-A193-66A3949FCBF6}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {EA02FF95-08F8-4D3D-A193-66A3949FCBF6}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {EA02FF95-08F8-4D3D-A193-66A3949FCBF6}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {1D0CDAA5-9CA7-4DFA-847E-35BD51AD492C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {1D0CDAA5-9CA7-4DFA-847E-35BD51AD492C}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {1D0CDAA5-9CA7-4DFA-847E-35BD51AD492C}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {1D0CDAA5-9CA7-4DFA-847E-35BD51AD492C}.Release|Any CPU.Build.0 = Release|Any CPU 36 | {C61FFB41-CB51-477F-BED2-BDCDA3105038}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 37 | {C61FFB41-CB51-477F-BED2-BDCDA3105038}.Debug|Any CPU.Build.0 = Debug|Any CPU 38 | {C61FFB41-CB51-477F-BED2-BDCDA3105038}.Release|Any CPU.ActiveCfg = Release|Any CPU 39 | {C61FFB41-CB51-477F-BED2-BDCDA3105038}.Release|Any CPU.Build.0 = Release|Any CPU 40 | {E7963BF5-5687-47BE-A8EF-687C48680354}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 41 | {E7963BF5-5687-47BE-A8EF-687C48680354}.Debug|Any CPU.Build.0 = Debug|Any CPU 42 | {E7963BF5-5687-47BE-A8EF-687C48680354}.Release|Any CPU.ActiveCfg = Release|Any CPU 43 | {E7963BF5-5687-47BE-A8EF-687C48680354}.Release|Any CPU.Build.0 = Release|Any CPU 44 | {BD66C9CB-B1D3-4A13-80AD-F6A4A7D7AAAF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 45 | {BD66C9CB-B1D3-4A13-80AD-F6A4A7D7AAAF}.Debug|Any CPU.Build.0 = Debug|Any CPU 46 | {BD66C9CB-B1D3-4A13-80AD-F6A4A7D7AAAF}.Release|Any CPU.ActiveCfg = Release|Any CPU 47 | {BD66C9CB-B1D3-4A13-80AD-F6A4A7D7AAAF}.Release|Any CPU.Build.0 = Release|Any CPU 48 | EndGlobalSection 49 | GlobalSection(SolutionProperties) = preSolution 50 | HideSolutionNode = FALSE 51 | EndGlobalSection 52 | GlobalSection(ExtensibilityGlobals) = postSolution 53 | SolutionGuid = {4D5BF36C-568D-437D-AEC2-4F6D8961CD45} 54 | EndGlobalSection 55 | EndGlobal 56 | -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation/Internal/ValidationInterceptor.cs: -------------------------------------------------------------------------------- 1 | using Grpc.Core; 2 | using Grpc.Core.Interceptors; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace Calzolari.Grpc.AspNetCore.Validation.Internal 7 | { 8 | internal class ValidationInterceptor : Interceptor 9 | { 10 | private readonly IValidatorLocator _locator; 11 | private readonly IValidatorErrorMessageHandler _handler; 12 | 13 | public ValidationInterceptor(IValidatorLocator locator, IValidatorErrorMessageHandler handler) 14 | { 15 | _locator = locator; 16 | _handler = handler; 17 | } 18 | public override async Task UnaryServerHandler(TRequest request, 19 | ServerCallContext context, 20 | UnaryServerMethod continuation) 21 | { 22 | await ValidateRequest(request); 23 | return await continuation(request, context); 24 | } 25 | 26 | public override async Task ServerStreamingServerHandler(TRequest request, 27 | IServerStreamWriter responseStream, 28 | ServerCallContext context, 29 | ServerStreamingServerMethod continuation) 30 | { 31 | await ValidateRequest(request); 32 | await continuation(request, responseStream, context); 33 | } 34 | 35 | public override async Task ClientStreamingServerHandler(IAsyncStreamReader requestStream, 36 | ServerCallContext context, 37 | ClientStreamingServerMethod continuation) 38 | { 39 | var validatingRequestStream = new ValidatingAsyncStreamReader(requestStream, request => ValidateRequest(request)); 40 | return await continuation(validatingRequestStream, context); 41 | } 42 | 43 | public override async Task DuplexStreamingServerHandler(IAsyncStreamReader requestStream, 44 | IServerStreamWriter responseStream, 45 | ServerCallContext context, 46 | DuplexStreamingServerMethod continuation) 47 | { 48 | var validatingRequestStream = new ValidatingAsyncStreamReader(requestStream, request => ValidateRequest(request)); 49 | await continuation(validatingRequestStream, responseStream, context); 50 | } 51 | 52 | private async Task ValidateRequest(TRequest request) where TRequest : class 53 | { 54 | if (_locator.TryGetValidator(out var validator)) 55 | { 56 | var results = await validator.ValidateAsync(request); 57 | 58 | if (!results.IsValid && results.Errors.Any()) 59 | { 60 | var message = await _handler.HandleAsync(results.Errors); 61 | var validationMetadata = results.Errors.ToValidationMetadata(); 62 | throw new ValidationRpcException(new Status(StatusCode.InvalidArgument, message), validationMetadata); 63 | } 64 | } 65 | } 66 | } 67 | } -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation/ServiceCollectionHelper.cs: -------------------------------------------------------------------------------- 1 | using Calzolari.Grpc.AspNetCore.Validation.Internal; 2 | using FluentValidation; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using System; 5 | using System.Linq; 6 | 7 | namespace Calzolari.Grpc.AspNetCore.Validation; 8 | 9 | public static class ServiceCollectionHelper 10 | { 11 | /// 12 | /// Add default component for validating grpc messages 13 | /// 14 | /// service collection 15 | /// service collection 16 | public static IServiceCollection AddGrpcValidation(this IServiceCollection services) 17 | { 18 | services.AddScoped(provider => new ServiceCollectionValidationProvider(provider)); 19 | 20 | if (services.All(r => r.ServiceType != typeof(IValidatorErrorMessageHandler))) 21 | services.AddSingleton(); 22 | 23 | return services; 24 | } 25 | 26 | /// 27 | /// Add custom message validator. 28 | /// 29 | /// service collection 30 | /// specific life time for validator 31 | /// custom validator type 32 | /// 33 | /// When try to register along validator class. 34 | public static IServiceCollection AddValidator(this IServiceCollection services, 35 | ServiceLifetime lifetime = ServiceLifetime.Scoped) where TValidator : class 36 | { 37 | var implementationType = typeof(TValidator); 38 | var validatorType = implementationType.GetInterfaces().FirstOrDefault(t => 39 | t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IValidator<>)); 40 | 41 | if (validatorType == null) 42 | throw new AggregateException(implementationType.Name + "is not implement with IValidator<>."); 43 | 44 | var messageType = validatorType.GetGenericArguments().First(); 45 | var serviceType = typeof(IValidator<>).MakeGenericType(messageType); 46 | 47 | services.Add(new ServiceDescriptor(serviceType, implementationType, lifetime)); 48 | return services; 49 | } 50 | 51 | /// 52 | /// Add all custom message validators. 53 | /// 54 | /// service collection 55 | /// specific life time for validator 56 | /// 57 | /// When try to register along validator class. 58 | public static IServiceCollection AddValidators(this IServiceCollection services, 59 | ServiceLifetime lifetime = ServiceLifetime.Scoped) 60 | { 61 | var implementationTypes = AppDomain.CurrentDomain 62 | .GetAssemblies() 63 | .SelectMany(x => x.GetTypes()) 64 | .Where(t => t.GetInterface(typeof(IValidator<>).FullName) != null) 65 | .Where(t => !t.Name.Contains("InlineValidator") && !t.Name.Contains("AbstractValidator")) 66 | .ToList(); 67 | 68 | foreach (var implementationType in implementationTypes) 69 | { 70 | var validatorType = implementationType.GetInterfaces() 71 | .FirstOrDefault(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IValidator<>)); 72 | 73 | if (validatorType == null) 74 | throw new AggregateException(implementationType.Name + "is not implement with IValidator<>."); 75 | 76 | var messageType = validatorType.GetGenericArguments().First(); 77 | var serviceType = typeof(IValidator<>).MakeGenericType(messageType); 78 | 79 | services.Add(new ServiceDescriptor(serviceType, implementationType, lifetime)); 80 | } 81 | 82 | return services; 83 | } 84 | 85 | /// 86 | /// Add inline validator for simple rule. 87 | /// 88 | /// service collection 89 | /// configure validation rules 90 | /// grpc message type 91 | /// 92 | public static IServiceCollection AddInlineValidator(this IServiceCollection services, 93 | Action> validator) 94 | { 95 | services.AddSingleton>(new Validation.InlineValidator(validator)); 96 | return services; 97 | } 98 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # grpc-aspnetcore-validator 2 | Request message validator middleware for [Grpc.AspNetCore](https://github.com/grpc/grpc-dotnet). 3 | Compatible with gRPC and gRPC-web C# clients 4 | 5 | ![](https://github.com/AnthonyGiretti/grpc-aspnetcore-validator/workflows/Build/badge.svg) 6 | [![Nuget](https://img.shields.io/nuget/v/Calzolari.Grpc.AspNetCore.Validation)](https://www.nuget.org/packages/Calzolari.Grpc.AspNetCore.Validation) 7 | 8 | ## Features 9 | 10 | - Server Side validation 11 | - Client Side detailed errors fetching in RpcException 12 | 13 | ### Client Side usage 14 | 15 | Download the client side package here: [Calzolari.Grpc.Net.Client.Validation](https://www.nuget.org/packages/Calzolari.Grpc.Net.Client.Validation/) 16 | 17 | ```csharp 18 | try 19 | { 20 | 21 | using var channel = GrpcChannel.ForAddress("https://localhost:5001"); 22 | var client = new Greeter.GreeterClient(channel); 23 | // Empty value that raises an error validation 24 | var reply = await client.SayHelloAsync(new HelloRequest { Name = "" }); 25 | } 26 | catch (RpcException e) when (ex.StatusCode == StatusCode.InvalidArgument) 27 | { 28 | var errors = e.GetValidationErrors(); // Gets validation errors list 29 | } 30 | ``` 31 | 32 | If you are using Blazor WebAssembly client-side (or any JavaScript client), don't forget to setup gRPC-web on the server and CORS rules with the following headers server-side: 33 | 34 | ```csharp 35 | .WithExposedHeaders("Grpc-Status", "Grpc-Message", "Grpc-Encoding", "Grpc-Accept-Encoding", "validation-errors-text"); 36 | ``` 37 | 38 | ### Server Side usage 39 | 40 | Download the server side package here: [Calzolari.Grpc.AspNetCore.Validation](https://www.nuget.org/packages/Calzolari.Grpc.AspNetCore.Validation/) 41 | 42 | This package is integrated with [Fluent Validation](https://github.com/JeremySkinner/FluentValidation). 43 | If you want to know how build your own validation rules, please checkout [Fluent Validation Docs](https://fluentvalidation.net/start) 44 | 45 | #### Add custom message validator 46 | 47 | ```csharp 48 | // Write own message validator 49 | public class HelloRequestValidator : AbstractValidator 50 | { 51 | public HelloRequestValidator() 52 | { 53 | RuleFor(request => request.Name).NotEmpty(); 54 | } 55 | } 56 | ``` 57 | 58 | ```csharp 59 | public class Startup 60 | { 61 | // ... 62 | public void ConfigureServices(IServiceCollection services) 63 | { 64 | // 1. Enable message validation feature. 65 | services.AddGrpc(options => options.EnableMessageValidation()); 66 | 67 | // 2-1. Add custom validators for messages one by one, default scope is scoped. 68 | services.AddValidator(); 69 | services.AddValidator(LifeStyle.Singleton); 70 | 71 | // 2-2. Add ALL custom validators for messages, default scope is scoped. 72 | services.AddValidators(); 73 | 74 | // 3. Add Validator locator 75 | services.AddGrpcValidation(); 76 | } 77 | // ... 78 | } 79 | ``` 80 | 81 | Then, If the message is invalid, Grpc Validator return with `InvalidArgument` code and empty message object. 82 | 83 | #### Add inline custom validator 84 | 85 | if you don't want to create many validation class for simple validation rule in your project, 86 | you just use below inline validator feature like below example. 87 | 88 | Note that, Inline validator always be registered **singleton** in your service collection. 89 | Because, There are no way for using other dependency. 90 | 91 | ```csharp 92 | public class Startup 93 | { 94 | // ... 95 | public void ConfigureServices(IServiceCollection services) 96 | { 97 | // 1. Enable message validation feature. 98 | services.AddGrpc(options => options.EnableMessageValidation()); 99 | 100 | // 2. Add inline validators for messages, scope is always singleton 101 | services.AddInlineValidator(rules => rules.RuleFor(request => request.Name).NotEmpty()); 102 | 103 | // 3. Add Validator locator 104 | services.AddGrpcValidation(); 105 | } 106 | // ... 107 | } 108 | ``` 109 | 110 | #### Customize validation failure message. 111 | 112 | If you want to custom validation message handler for using your own error message system, 113 | Just implement IValidatorErrorMessageHandler and put it service collection. 114 | 115 | ```csharp 116 | public class CustomMessageHandler : IValidatorErrorMessageHandler 117 | { 118 | public Task HandleAsync(IList failures) 119 | { 120 | return Task.FromResult("Validation Error!"); 121 | } 122 | } 123 | 124 | public class Startup 125 | { 126 | // ... 127 | public void ConfigureServices(IServiceCollection services) 128 | { 129 | services.AddGrpc(options => options.EnableMessageValidation()); 130 | services.AddInlineValidator(rules => rules.RuleFor(request => request.Name).NotEmpty()); 131 | 132 | // 1. Just put at service collection your own custom message handler that implement IValidatorErrorMessageHandler. 133 | // This should be placed before calling AddGrpcValidation(); 134 | services.AddSingleton(new CustomMessageHandler()) 135 | 136 | // If you don't reigster any message handler, AddGrpcValidation register default message handler. 137 | services.AddGrpcValidation(); 138 | } 139 | // ... 140 | } 141 | ``` 142 | 143 | #### Catch Server Side validation errors 144 | 145 | ```csharp 146 | try 147 | { 148 | //... 149 | } 150 | catch (ValidationRpcException ex) 151 | { 152 | // Handle any validation exceptions that occur during the process 153 | } 154 | ``` 155 | 156 | ## How to test validation 157 | 158 | If you want to write integration tests. [This test sample](https://github.com/AnthonyGiretti/grpc-aspnetcore-validator/tree/master/src/Calzolari.Grpc.AspNetCore.Validation.Test/Integration) may help you. 159 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | -------------------------------------------------------------------------------- /src/Calzolari.Grpc.AspNetCore.Validation.Test/Integration/CustomMessageHandlerIntegrationTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Calzolari.Grpc.AspNetCore.Validation.SampleRpc; 3 | using FluentValidation; 4 | using FluentValidation.Results; 5 | using Grpc.Core; 6 | using Microsoft.AspNetCore.Mvc.Testing; 7 | using Microsoft.AspNetCore.TestHost; 8 | using Microsoft.Extensions.DependencyInjection; 9 | using System.Collections.Generic; 10 | using System.Threading.Tasks; 11 | using Xunit; 12 | 13 | namespace Calzolari.Grpc.AspNetCore.Validation.Test.Integration 14 | { 15 | public class CustomMessageHandlerIntegrationTest : IClassFixture> 16 | { 17 | public CustomMessageHandlerIntegrationTest(WebApplicationFactory factory) 18 | { 19 | _factory = factory 20 | .WithWebHostBuilder(builder => builder.ConfigureTestServices(services => 21 | { 22 | services.AddInlineValidator(rules => 23 | { 24 | rules.RuleFor(r => r.Name).NotEmpty(); 25 | }); 26 | services.AddSingleton(new CustomMessageHandler()); 27 | services.AddGrpcValidation(); 28 | })); 29 | } 30 | 31 | private readonly WebApplicationFactory _factory; 32 | 33 | [Fact] 34 | public async Task Should_ThrowInvalidArgument_When_NameOfMessageIsEmpty() 35 | { 36 | // Given 37 | var client = new Greeter.GreeterClient(_factory.CreateGrpcChannel()); 38 | 39 | // When 40 | async Task Action() 41 | { 42 | await client.SayHelloAsync(new HelloRequest {Name = string.Empty}); 43 | } 44 | 45 | // Then 46 | var rpcException = await Assert.ThrowsAsync(Action); 47 | Assert.Equal(StatusCode.InvalidArgument, rpcException.Status.StatusCode); 48 | Assert.Equal("Validation Error!", rpcException.Status.Detail); 49 | } 50 | 51 | [Fact] 52 | public async Task Should_ThrowInvalidArgument_When_NameOfMessageIsEmpty_ForServerStreaming() 53 | { 54 | // Given 55 | var client = new Greeter.GreeterClient(_factory.CreateGrpcChannel()); 56 | 57 | // When 58 | async Task Action() 59 | { 60 | using var stream = client.SayHelloServerStreaming(new HelloRequest { Name = string.Empty }); 61 | await foreach (var message in stream.ResponseStream.ReadAllAsync()) 62 | { 63 | } 64 | } 65 | 66 | // Then 67 | var rpcException = await Assert.ThrowsAsync(Action); 68 | Assert.Equal(StatusCode.InvalidArgument, rpcException.Status.StatusCode); 69 | Assert.Equal("Validation Error!", rpcException.Status.Detail); 70 | } 71 | 72 | [Fact] 73 | public async Task Should_ThrowInvalidArgument_When_NameOfMessageIsEmpty_ForClientStreaming() 74 | { 75 | // Given 76 | var client = new Greeter.GreeterClient(_factory.CreateGrpcChannel()); 77 | 78 | // When 79 | async Task Action() 80 | { 81 | using var request = client.SayHelloClientStreaming(); 82 | 83 | await request.RequestStream.WriteAsync(new HelloRequest {Name = "Alice"}); 84 | await request.RequestStream.WriteAsync(new HelloRequest {Name = "Bob"}); 85 | await request.RequestStream.WriteAsync(new HelloRequest {Name = string.Empty}); 86 | await request.RequestStream.CompleteAsync(); 87 | 88 | var result = await request; 89 | } 90 | 91 | // Then 92 | var rpcException = await Assert.ThrowsAsync(Action); 93 | Assert.Equal(StatusCode.InvalidArgument, rpcException.Status.StatusCode); 94 | Assert.Equal("Validation Error!", rpcException.Status.Detail); 95 | } 96 | 97 | [Fact] 98 | public async Task Should_NotThrow_When_Valid_ForClientStreaming() 99 | { 100 | // Given 101 | var client = new Greeter.GreeterClient(_factory.CreateGrpcChannel()); 102 | 103 | // When 104 | async Task Action() 105 | { 106 | using var request = client.SayHelloClientStreaming(); 107 | 108 | await request.RequestStream.WriteAsync(new HelloRequest { Name = "Alice" }); 109 | await request.RequestStream.WriteAsync(new HelloRequest { Name = "Bob" }); 110 | await request.RequestStream.WriteAsync(new HelloRequest { Name = "Charlie" }); 111 | await request.RequestStream.CompleteAsync(); 112 | 113 | return await request; 114 | } 115 | 116 | // Then 117 | var reply = await Action(); 118 | Assert.Equal("Hello Alice, Bob, Charlie", reply.Message); 119 | } 120 | 121 | [Fact] 122 | public async Task Should_ThrowInvalidArgument_When_NameOfMessageIsEmpty_ForDuplexStreaming() 123 | { 124 | // Given 125 | var client = new Greeter.GreeterClient(_factory.CreateGrpcChannel()); 126 | 127 | // When 128 | async Task Action() 129 | { 130 | using var request = client.SayHelloDuplexStreaming(); 131 | 132 | await request.RequestStream.WriteAsync(new HelloRequest { Name = "Alice" }); 133 | await request.RequestStream.WriteAsync(new HelloRequest { Name = "Bob" }); 134 | await request.RequestStream.WriteAsync(new HelloRequest { Name = string.Empty }); 135 | await request.RequestStream.CompleteAsync(); 136 | 137 | await foreach (var response in request.ResponseStream.ReadAllAsync()) 138 | { 139 | } 140 | } 141 | 142 | // Then 143 | var rpcException = await Assert.ThrowsAsync(Action); 144 | Assert.Equal(StatusCode.InvalidArgument, rpcException.Status.StatusCode); 145 | Assert.Equal("Validation Error!", rpcException.Status.Detail); 146 | } 147 | 148 | [Fact] 149 | public async Task Should_NotThrow_When_Valid_ForDuplexStreaming() 150 | { 151 | // Given 152 | var client = new Greeter.GreeterClient(_factory.CreateGrpcChannel()); 153 | var names = new[] {"Alice", "Bob", "Charlie"}; 154 | 155 | // When 156 | async Task> Action() 157 | { 158 | using var request = client.SayHelloDuplexStreaming(); 159 | 160 | foreach (var name in names) 161 | { 162 | await request.RequestStream.WriteAsync(new HelloRequest { Name = name }); 163 | } 164 | await request.RequestStream.CompleteAsync(); 165 | 166 | var messages = new List(); 167 | await foreach (var response in request.ResponseStream.ReadAllAsync()) 168 | { 169 | messages.Add(response.Message); 170 | } 171 | 172 | return messages; 173 | } 174 | 175 | // Then 176 | var messages = await Action(); 177 | Assert.Collection(messages, 178 | m => Assert.Equal("Hello Alice", m), 179 | m => Assert.Equal("Hello Bob", m), 180 | m => Assert.Equal("Hello Charlie", m) 181 | ); 182 | } 183 | 184 | class CustomMessageHandler : IValidatorErrorMessageHandler 185 | { 186 | public Task HandleAsync(IList failures) 187 | { 188 | return Task.FromResult("Validation Error!"); 189 | } 190 | } 191 | } 192 | } --------------------------------------------------------------------------------