├── .github └── workflows │ ├── build.yml │ ├── deploy_nuget.yml │ └── test.yml ├── .gitignore ├── LICENSE ├── README.md ├── build └── version.props └── src ├── Grpc.AspNetCore.FluentValidation.SampleRpc ├── Grpc.AspNetCore.FluentValidation.SampleRpc.csproj ├── Program.cs ├── Properties │ └── launchSettings.json ├── Protos │ └── greet.proto ├── Services │ └── GreeterService.cs ├── Startup.cs ├── appsettings.Development.json └── appsettings.json ├── Grpc.AspNetCore.FluentValidation.Test ├── Grpc.AspNetCore.FluentValidation.Test.csproj ├── Integration │ ├── CustomMessageHandlerIntegrationTest.cs │ ├── CustomValidatorIntegrationTest.cs │ ├── InlineValidatorIntegrationTest.cs │ └── ValidatorProfileIntegrationTest.cs ├── ServiceCollectionHelperTest.cs └── WebApplicationFactoryHelper.cs ├── Grpc.AspNetCore.FluentValidation.sln ├── Grpc.AspNetCore.FluentValidation.sln.DotSettings └── Grpc.AspNetCore.FluentValidation ├── Grpc.AspNetCore.FluentValidation.csproj ├── GrpcServiceOptionsHelper.cs ├── IValidatorErrorMessageHandler.cs ├── IValidatorLocator.cs ├── InlineValidator.cs ├── Internal ├── DefaultErrorMessageHandler.cs ├── ServiceCollectionValidationProvider.cs ├── TypeHelper.cs └── ValidationInterceptor.cs ├── ServiceCollectionHelper.cs └── ValidatorProfileBase.cs /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v1 10 | - name: Setup .NET Core 11 | uses: actions/setup-dotnet@v1 12 | with: 13 | dotnet-version: 3.1.100 14 | - name: Build with dotnet 15 | working-directory: src 16 | run: dotnet build --configuration Release 17 | -------------------------------------------------------------------------------- /.github/workflows/deploy_nuget.yml: -------------------------------------------------------------------------------- 1 | name: Deploy nuget 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | paths: 7 | - build/version.props 8 | 9 | jobs: 10 | deploy: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v2 14 | - name: Setup .NET Core 15 | uses: actions/setup-dotnet@v1 16 | with: 17 | dotnet-version: 3.1.101 18 | - name: Install dependencies 19 | run: dotnet restore 20 | working-directory: src 21 | - name: Build solution 22 | run: dotnet build --no-restore 23 | working-directory: src 24 | - name: Deploy nuget package to nuget 25 | run: dotnet nuget push *\bin\**\*.nupkg -k ${{ secrets.NUGETAPIKEY }} -s https://api.nuget.org/v3/index.json --skip-duplicate 26 | working-directory: src -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: [push] 4 | 5 | jobs: 6 | test: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v1 10 | - name: Setup .NET Core 11 | uses: actions/setup-dotnet@v1 12 | with: 13 | dotnet-version: 3.1.100 14 | - name: Test with dotnet 15 | working-directory: src/Grpc.AspNetCore.FluentValidation.Test 16 | run: dotnet test 17 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 enif.lee 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # grpc-dotnet-validator 2 | Request message validator middleware for [Grpc.AspNetCore](https://github.com/grpc/grpc-dotnet) 3 | 4 | ![](https://github.com/enif-lee/grpc-dotnet-validator/workflows/Build/badge.svg) 5 | ![](https://github.com/enif-lee/grpc-dotnet-validator/workflows/Test/badge.svg) 6 | [![Nuget](https://img.shields.io/nuget/v/GrpcExtensions.AspNetCore.Validation)](https://www.nuget.org/packages/GrpcExtensions.AspNetCore.Validation) 7 | 8 | 9 | ## Feature 10 | 11 | - Support async validation for unary, streaming call 12 | - Support IoC LifeStyle scopes and dependency injection 13 | - Profile for validators 14 | - Scan validators and profiles from assembly 15 | 16 | ## How to use. 17 | 18 | This package is integrated with [Fluent Validation](https://github.com/JeremySkinner/FluentValidation). 19 | If you want to know how build your own validation rules, please checkout [Fluent Validation Docs](https://fluentvalidation.net/start) 20 | 21 | #### Add custom message validator 22 | 23 | ```csharp 24 | // Write own message validator 25 | public class HelloRequestValidator : AbstractValidator 26 | { 27 | public HelloRequestValidator() 28 | { 29 | RuleFor(request => request.Name).NotEmpty(); 30 | } 31 | } 32 | 33 | public class Startup 34 | { 35 | // ... 36 | public void ConfigureServices(IServiceCollection services) 37 | { 38 | // 1. Enable message validation feature. 39 | services.AddGrpc(options => options.EnableMessageValidation()); 40 | 41 | // 2. Add custom validators for messages, default scope is scope. 42 | services.AddValidator(typeof(HelloRequestValidator)); 43 | services.AddValidator(); 44 | services.AddValidator(LifeStyle.Singleton); 45 | } 46 | // ... 47 | } 48 | ``` 49 | 50 | Then, If the message is invalid, Grpc Validator return with `InvalidArgument` code and empty message object. 51 | 52 | #### Add inline custom validator 53 | 54 | if you don't want to create many validation class for simple validation rule in your project, 55 | you just use below inline validator feature like below example. 56 | 57 | Note that, Inline validator always be registered **singleton** in your service collection. 58 | Because, There are no way for using other dependency. 59 | 60 | ```csharp 61 | public class Startup 62 | { 63 | // ... 64 | public void ConfigureServices(IServiceCollection services) 65 | { 66 | // 1. Enable message validation feature. 67 | services.AddGrpc(options => options.EnableMessageValidation()); 68 | 69 | // 2. Add inline validators for messages, scope is always singleton 70 | services.AddInlineValidator(rules => rules.RuleFor(request => request.Name).NotEmpty()); 71 | } 72 | // ... 73 | } 74 | ``` 75 | 76 | 77 | #### Profiling validators 78 | 79 | If you don't want to make a mess your startup class by registering validators, you implement validator profile and use it. 80 | 81 | ```cs 82 | public class SampleProfile : ValidatorProfileBase 83 | { 84 | public SampleProfile() 85 | { 86 | CreateInlineValidator() 87 | .RuleFor(r => r.Data).NotNull().NotEmpty() 88 | .RuleFor(r => r.Name).NotNull(); 89 | AddValidator(); 90 | AddValidator(ServiceLifetime.Singleton); 91 | } 92 | } 93 | 94 | // Then in your Startup class 95 | public void ConfigureServices(IServiceCollection services) 96 | { 97 | services.AddGrpc(options => options.EnableMessageValidation()); 98 | services.AddValidatorProfile(); 99 | } 100 | ``` 101 | 102 | #### Scan and register profiles/validators from assembly. 103 | 104 | 105 | ```cs 106 | // Place somewhere validator or profile class. 107 | public class HelloRequestValidator : AbstractValidator 108 | { 109 | public HelloRequestValidator() 110 | { 111 | RuleFor(request => request.Name).NotEmpty(); 112 | } 113 | } 114 | 115 | public class SampleProfile : ValidatorProfileBase 116 | { 117 | public SampleProfile() 118 | { 119 | CreateInlineValidator() 120 | .RuleFor(r => r.Data).NotNull().NotEmpty() 121 | .RuleFor(r => r.Name).NotNull(); 122 | AddValidator(); 123 | AddValidator(ServiceLifetime.Singleton); 124 | } 125 | } 126 | 127 | // Then in your Startup class 128 | public void ConfigureServices(IServiceCollection services) 129 | { 130 | services.AddGrpc(options => options.EnableMessageValidation()); 131 | 132 | // Scan profile and validators from calling assembly. 133 | services.AddValidatorsFromAssemblies(); 134 | services.AddProfilesFromAssembly(); 135 | 136 | // Scan profiles and validators from specific assembly. 137 | services.AddValidatorsFromAssemblies(typeof(InternalLibarary).Assembly); 138 | services.AddProfilesFromAssembly(typeof(InternalLibarary).Assembly); 139 | } 140 | ``` 141 | 142 | 143 | #### Customize validation failure message. 144 | 145 | If you want to custom validation message handler for using your own error message system, 146 | Just implement IValidatorErrorMessageHandler and put it service collection. 147 | 148 | ```csharp 149 | public class CustomMessageHandler : IValidatorErrorMessageHandler 150 | { 151 | public Task HandleAsync(IList failures) 152 | { 153 | return Task.FromResult("Validation Error!"); 154 | } 155 | } 156 | 157 | public class Startup 158 | { 159 | // ... 160 | public void ConfigureServices(IServiceCollection services) 161 | { 162 | services.AddGrpc(options => options.EnableMessageValidation()); 163 | 164 | // Just put at service collection your own custom message handler that implement IValidatorErrorMessageHnadler. 165 | // This should be placed before calling AddInlineValidator() or AddValidator(); 166 | services.AddSingleton(new CustomMessageHandler()) 167 | services.AddInlineValidator(rules => rules.RuleFor(request => request.Name).NotEmpty()); 168 | } 169 | // ... 170 | } 171 | ``` 172 | 173 | ## How to test my validation 174 | 175 | If you want to write integration tests. [This test sample](src/Grpc.AspNetCore.FluentValidation.Test/Integration/) may help you. 176 | 177 | 178 | ## Versioning 179 | 180 | This pakage`s versioning is following version of [Grpc.AspNetCore](https://github.com/grpc/grpc-dotnet) 181 | 182 | -------------------------------------------------------------------------------- /build/version.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 2.25.6 4 | 5 | -------------------------------------------------------------------------------- /src/Grpc.AspNetCore.FluentValidation.SampleRpc/Grpc.AspNetCore.FluentValidation.SampleRpc.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netcoreapp3.1 5 | false 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/Grpc.AspNetCore.FluentValidation.SampleRpc/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.Extensions.Hosting; 3 | 4 | namespace Grpc.AspNetCore.FluentValidation.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/Grpc.AspNetCore.FluentValidation.SampleRpc/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "Grpc.AspNetCore.FluentValidation.SampleRpc": { 4 | "commandName": "Project", 5 | "launchBrowser": false, 6 | "applicationUrl": "https://localhost:5001", 7 | "environmentVariables": { 8 | "ASPNETCORE_ENVIRONMENT": "Development" 9 | } 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/Grpc.AspNetCore.FluentValidation.SampleRpc/Protos/greet.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | option csharp_namespace = "Grpc.AspNetCore.FluentValidation.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 | } 12 | 13 | // The request message containing the user's name. 14 | message HelloRequest { 15 | string name = 1; 16 | } 17 | 18 | // The response message containing the greetings. 19 | message HelloReply { 20 | string message = 1; 21 | } 22 | -------------------------------------------------------------------------------- /src/Grpc.AspNetCore.FluentValidation.SampleRpc/Services/GreeterService.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Grpc.Core; 3 | using Microsoft.Extensions.Logging; 4 | 5 | namespace Grpc.AspNetCore.FluentValidation.SampleRpc.Services 6 | { 7 | public class GreeterService : Greeter.GreeterBase 8 | { 9 | private readonly ILogger _logger; 10 | 11 | public GreeterService(ILogger logger) 12 | { 13 | _logger = logger; 14 | } 15 | 16 | public override Task SayHello(HelloRequest request, ServerCallContext context) 17 | { 18 | return Task.FromResult(new HelloReply 19 | { 20 | Message = "Hello " + request.Name 21 | }); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /src/Grpc.AspNetCore.FluentValidation.SampleRpc/Startup.cs: -------------------------------------------------------------------------------- 1 | using Grpc.AspNetCore.FluentValidation.SampleRpc.Services; 2 | using Microsoft.AspNetCore.Builder; 3 | using Microsoft.AspNetCore.Hosting; 4 | using Microsoft.AspNetCore.Http; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.Hosting; 7 | 8 | namespace Grpc.AspNetCore.FluentValidation.SampleRpc 9 | { 10 | public class Startup 11 | { 12 | // This method gets called by the runtime. Use this method to add services to the container. 13 | // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 14 | public void ConfigureServices(IServiceCollection services) 15 | { 16 | services.AddGrpc(options => options.EnableMessageValidation()); 17 | } 18 | 19 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 20 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 21 | { 22 | if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); 23 | 24 | app.UseRouting(); 25 | 26 | app.UseEndpoints(endpoints => 27 | { 28 | endpoints.MapGrpcService(); 29 | 30 | endpoints.MapGet("/", 31 | async context => 32 | { 33 | await context.Response.WriteAsync( 34 | "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"); 35 | }); 36 | }); 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /src/Grpc.AspNetCore.FluentValidation.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/Grpc.AspNetCore.FluentValidation.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/Grpc.AspNetCore.FluentValidation.Test/Grpc.AspNetCore.FluentValidation.Test.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netcoreapp3.1 5 | false 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /src/Grpc.AspNetCore.FluentValidation.Test/Integration/CustomMessageHandlerIntegrationTest.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Net.Http; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | using FluentValidation; 6 | using FluentValidation.Results; 7 | using Grpc.AspNetCore.FluentValidation.SampleRpc; 8 | using Grpc.Core; 9 | using Microsoft.AspNetCore.Mvc.Testing; 10 | using Microsoft.AspNetCore.TestHost; 11 | using Microsoft.Extensions.DependencyInjection; 12 | using Xunit; 13 | 14 | namespace Grpc.AspNetCore.FluentValidation.Test.Integration 15 | { 16 | public class CustomMessageHandlerIntegrationTest : IClassFixture> 17 | { 18 | public CustomMessageHandlerIntegrationTest(WebApplicationFactory factory) 19 | { 20 | _factory = factory 21 | .WithWebHostBuilder(builder => builder.ConfigureTestServices(services => 22 | { 23 | services.AddInlineValidator(rules => 24 | { 25 | rules.RuleFor(r => r.Name).NotEmpty(); 26 | }); 27 | services.AddSingleton(new CustomMessageHandler()); 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 | class CustomMessageHandler : IValidatorErrorMessageHandler 52 | { 53 | public Task HandleAsync(IList failures) 54 | { 55 | return Task.FromResult("Validation Error!"); 56 | } 57 | } 58 | } 59 | } -------------------------------------------------------------------------------- /src/Grpc.AspNetCore.FluentValidation.Test/Integration/CustomValidatorIntegrationTest.cs: -------------------------------------------------------------------------------- 1 | using System.Net.Http; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using FluentValidation; 5 | using Grpc.AspNetCore.FluentValidation.SampleRpc; 6 | using Grpc.Core; 7 | using Microsoft.AspNetCore.Mvc.Testing; 8 | using Microsoft.AspNetCore.TestHost; 9 | using Xunit; 10 | 11 | namespace Grpc.AspNetCore.FluentValidation.Test.Integration 12 | { 13 | public class CustomValidatorIntegrationTest : IClassFixture> 14 | { 15 | public CustomValidatorIntegrationTest(WebApplicationFactory factory) 16 | { 17 | _factory = factory 18 | .WithWebHostBuilder(builder => builder.ConfigureTestServices(services => 19 | { 20 | services.AddValidator(); 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 | [Fact] 59 | public async Task Should_ReturnWithTrailingHeader_When_RequestIsInvalid() 60 | { 61 | // Given 62 | var spyHandler = new VerifierHeaderSpyDelegate(); 63 | var client = new Greeter.GreeterClient(_factory.CreateGrpcChannel(spyHandler)); 64 | 65 | // When 66 | await client.SayHelloAsync(new HelloRequest {Name = string.Empty}).ResponseHeadersAsync; 67 | 68 | // Then 69 | var headers = spyHandler.ResponseMessage.Headers; 70 | headers.TryGetValues("grpc-status", out var values); 71 | Assert.Single(values, "3"); 72 | Assert.True(headers.Contains("grpc-message")); 73 | } 74 | 75 | class VerifierHeaderSpyDelegate : ResponseVersionHandler 76 | { 77 | public HttpResponseMessage ResponseMessage { get; set; } 78 | 79 | protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 80 | { 81 | ResponseMessage = await base.SendAsync(request, cancellationToken); 82 | return ResponseMessage; 83 | } 84 | } 85 | 86 | public class HelloRequestValidator : AbstractValidator 87 | { 88 | public HelloRequestValidator() 89 | { 90 | RuleFor(request => request.Name).NotEmpty(); 91 | } 92 | } 93 | } 94 | } -------------------------------------------------------------------------------- /src/Grpc.AspNetCore.FluentValidation.Test/Integration/InlineValidatorIntegrationTest.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using FluentValidation; 3 | using Grpc.AspNetCore.FluentValidation.SampleRpc; 4 | using Grpc.Core; 5 | using Microsoft.AspNetCore.Mvc.Testing; 6 | using Microsoft.AspNetCore.TestHost; 7 | using Xunit; 8 | 9 | namespace Grpc.AspNetCore.FluentValidation.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 | })); 23 | } 24 | 25 | private readonly WebApplicationFactory _factory; 26 | 27 | [Fact] 28 | public async Task Should_ResponseMessage_When_MessageIsValid() 29 | { 30 | // Given 31 | var client = new Greeter.GreeterClient(_factory.CreateGrpcChannel()); 32 | 33 | // When 34 | await client.SayHelloAsync(new HelloRequest 35 | { 36 | Name = "Not Empty Name" 37 | }); 38 | 39 | // Then nothing happen. 40 | } 41 | 42 | [Fact] 43 | public async Task Should_ThrowInvalidArgument_When_NameOfMessageIsEmpty() 44 | { 45 | // Given 46 | var client = new Greeter.GreeterClient(_factory.CreateGrpcChannel()); 47 | 48 | // When 49 | async Task Action() 50 | { 51 | await client.SayHelloAsync(new HelloRequest {Name = string.Empty}); 52 | } 53 | 54 | // Then 55 | var rpcException = await Assert.ThrowsAsync(Action); 56 | Assert.Equal(StatusCode.InvalidArgument, rpcException.Status.StatusCode); 57 | } 58 | } 59 | } -------------------------------------------------------------------------------- /src/Grpc.AspNetCore.FluentValidation.Test/Integration/ValidatorProfileIntegrationTest.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using FluentValidation; 3 | using Grpc.AspNetCore.FluentValidation.SampleRpc; 4 | using Grpc.Core; 5 | using Microsoft.AspNetCore.Mvc.Testing; 6 | using Microsoft.AspNetCore.TestHost; 7 | using Xunit; 8 | 9 | namespace Grpc.AspNetCore.FluentValidation.Test.Integration 10 | { 11 | public class ValidatorProfileIntegrationTest : IClassFixture> 12 | { 13 | public class HelloRequestValidatorProfile : ValidatorProfileBase 14 | { 15 | public HelloRequestValidatorProfile() 16 | { 17 | CreateInlineValidator() 18 | .RuleFor(r => r.Name).NotEmpty(); 19 | } 20 | } 21 | 22 | public ValidatorProfileIntegrationTest(WebApplicationFactory factory) 23 | { 24 | _factory = factory 25 | .WithWebHostBuilder(builder => builder.ConfigureTestServices(services => 26 | { 27 | services.AddValidatorProfile(); 28 | })); 29 | } 30 | 31 | private readonly WebApplicationFactory _factory; 32 | 33 | [Fact] 34 | public async Task Should_ResponseMessage_When_MessageIsValid() 35 | { 36 | // Given 37 | var client = new Greeter.GreeterClient(_factory.CreateGrpcChannel()); 38 | 39 | // When 40 | await client.SayHelloAsync(new HelloRequest 41 | { 42 | Name = "Not Empty Name" 43 | }); 44 | 45 | // Then nothing happen. 46 | } 47 | 48 | [Fact] 49 | public async Task Should_ThrowInvalidArgument_When_NameOfMessageIsEmpty() 50 | { 51 | // Given 52 | var client = new Greeter.GreeterClient(_factory.CreateGrpcChannel()); 53 | 54 | // When 55 | async Task Action() 56 | { 57 | await client.SayHelloAsync(new HelloRequest {Name = string.Empty}); 58 | } 59 | 60 | // Then 61 | var rpcException = await Assert.ThrowsAsync(Action); 62 | Assert.Equal(StatusCode.InvalidArgument, rpcException.Status.StatusCode); 63 | } 64 | } 65 | } -------------------------------------------------------------------------------- /src/Grpc.AspNetCore.FluentValidation.Test/ServiceCollectionHelperTest.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | using Grpc.AspNetCore.FluentValidation.Internal; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Xunit; 5 | 6 | namespace Grpc.AspNetCore.FluentValidation.Test 7 | { 8 | public class ServiceCollectionHelperTest 9 | { 10 | [Fact] 11 | public void RegisterValidatorTest() 12 | { 13 | // Given 14 | var services = new ServiceCollection(); 15 | 16 | // When 17 | services.AddValidator(); 18 | var provider = services.BuildServiceProvider(); 19 | 20 | // Then 21 | provider.GetRequiredService>(); 22 | } 23 | } 24 | 25 | 26 | public class TestValidator : AbstractValidator 27 | { 28 | } 29 | 30 | public class TestMessage 31 | { 32 | public string Message { get; set; } 33 | } 34 | } -------------------------------------------------------------------------------- /src/Grpc.AspNetCore.FluentValidation.Test/WebApplicationFactoryHelper.cs: -------------------------------------------------------------------------------- 1 | using System.Net.Http; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using Grpc.AspNetCore.FluentValidation.SampleRpc; 5 | using Grpc.Net.Client; 6 | using Microsoft.AspNetCore.Mvc.Testing; 7 | 8 | namespace Grpc.AspNetCore.FluentValidation.Test 9 | { 10 | public static class WebApplicationFactoryHelper 11 | { 12 | public static GrpcChannel CreateGrpcChannel(this WebApplicationFactory factory) 13 | { 14 | return CreateGrpcChannel(factory, new ResponseVersionHandler()); 15 | } 16 | 17 | public static GrpcChannel CreateGrpcChannel(this WebApplicationFactory factory, DelegatingHandler handler) 18 | { 19 | var client = factory.CreateDefaultClient(handler); 20 | return GrpcChannel.ForAddress(client.BaseAddress, new GrpcChannelOptions 21 | { 22 | HttpClient = client 23 | }); 24 | } 25 | 26 | } 27 | 28 | internal class ResponseVersionHandler : DelegatingHandler 29 | { 30 | protected override async Task SendAsync(HttpRequestMessage request, 31 | CancellationToken cancellationToken) 32 | { 33 | var response = await base.SendAsync(request, cancellationToken); 34 | response.Version = request.Version; 35 | 36 | return response; 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /src/Grpc.AspNetCore.FluentValidation.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Items", "Items", "{A041C68C-F36B-4DCE-A8BA-0442A8121F62}" 4 | ProjectSection(SolutionItems) = preProject 5 | ..\README.md = ..\README.md 6 | EndProjectSection 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Grpc.AspNetCore.FluentValidation", "Grpc.AspNetCore.FluentValidation\Grpc.AspNetCore.FluentValidation.csproj", "{F55AB3D4-520D-42C4-A609-4355191B5F12}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Grpc.AspNetCore.FluentValidation.SampleRpc", "Grpc.AspNetCore.FluentValidation.SampleRpc\Grpc.AspNetCore.FluentValidation.SampleRpc.csproj", "{03EA42CC-AAFA-4FC7-B41F-C18B1527D33B}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Grpc.AspNetCore.FluentValidation.Test", "Grpc.AspNetCore.FluentValidation.Test\Grpc.AspNetCore.FluentValidation.Test.csproj", "{877025FA-4534-4C44-8C75-79776A1D57BA}" 13 | EndProject 14 | Global 15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 16 | Debug|Any CPU = Debug|Any CPU 17 | Release|Any CPU = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {F55AB3D4-520D-42C4-A609-4355191B5F12}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {F55AB3D4-520D-42C4-A609-4355191B5F12}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {F55AB3D4-520D-42C4-A609-4355191B5F12}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {F55AB3D4-520D-42C4-A609-4355191B5F12}.Release|Any CPU.Build.0 = Release|Any CPU 24 | {03EA42CC-AAFA-4FC7-B41F-C18B1527D33B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {03EA42CC-AAFA-4FC7-B41F-C18B1527D33B}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {03EA42CC-AAFA-4FC7-B41F-C18B1527D33B}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {03EA42CC-AAFA-4FC7-B41F-C18B1527D33B}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {877025FA-4534-4C44-8C75-79776A1D57BA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {877025FA-4534-4C44-8C75-79776A1D57BA}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {877025FA-4534-4C44-8C75-79776A1D57BA}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {877025FA-4534-4C44-8C75-79776A1D57BA}.Release|Any CPU.Build.0 = Release|Any CPU 32 | EndGlobalSection 33 | EndGlobal 34 | -------------------------------------------------------------------------------- /src/Grpc.AspNetCore.FluentValidation.sln.DotSettings: -------------------------------------------------------------------------------- 1 |  2 | True -------------------------------------------------------------------------------- /src/Grpc.AspNetCore.FluentValidation/Grpc.AspNetCore.FluentValidation.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | GrpcExtensions.AspNetCore.Validation 5 | Jinseoung Lee 6 | grpc;dotnet;validator;validation;request-validation;aspnetcore 7 | true 8 | https://github.com/enif-lee/grpc-dotnet-validator 9 | https://github.com/enif-lee/grpc-dotnet-validator/blob/master/LICENSE 10 | netcoreapp3.1 11 | bin\Debug\Grpc.AspNetCore.FluentValidation.xml 12 | snupkg 13 | true 14 | true 15 | https://github.com/enif-lee/grpc-dotnet-validator 16 | 17 | 18 | 19 | bin\Release\Grpc.AspNetCore.FluentValidation.xml 20 | 21 | 22 | 23 | bin\Debug\Grpc.AspNetCore.FluentValidation.xml 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /src/Grpc.AspNetCore.FluentValidation/GrpcServiceOptionsHelper.cs: -------------------------------------------------------------------------------- 1 | using Grpc.AspNetCore.FluentValidation.Internal; 2 | using Grpc.AspNetCore.Server; 3 | 4 | namespace Grpc.AspNetCore.FluentValidation 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 | } 14 | } -------------------------------------------------------------------------------- /src/Grpc.AspNetCore.FluentValidation/IValidatorErrorMessageHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using FluentValidation.Results; 4 | 5 | namespace Grpc.AspNetCore.FluentValidation 6 | { 7 | public interface IValidatorErrorMessageHandler 8 | { 9 | Task HandleAsync(IList failures); 10 | } 11 | } -------------------------------------------------------------------------------- /src/Grpc.AspNetCore.FluentValidation/IValidatorLocator.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | 3 | namespace Grpc.AspNetCore.FluentValidation 4 | { 5 | public interface IValidatorLocator 6 | { 7 | bool TryGetValidator(out IValidator result) where TRequest : class; 8 | } 9 | } -------------------------------------------------------------------------------- /src/Grpc.AspNetCore.FluentValidation/InlineValidator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using FluentValidation; 3 | 4 | namespace Grpc.AspNetCore.FluentValidation 5 | { 6 | public class InlineValidator : AbstractValidator 7 | { 8 | public InlineValidator() 9 | { 10 | } 11 | 12 | public InlineValidator(Action> configureRules) 13 | { 14 | configureRules(this); 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /src/Grpc.AspNetCore.FluentValidation/Internal/DefaultErrorMessageHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Threading.Tasks; 4 | using FluentValidation.Results; 5 | 6 | namespace Grpc.AspNetCore.FluentValidation.Internal 7 | { 8 | internal class DefaultErrorMessageHandler : IValidatorErrorMessageHandler 9 | { 10 | public Task HandleAsync(IList failures) 11 | { 12 | var errors = failures 13 | .Select(f => $"Property {f.PropertyName} failed validation. Error was {f.ErrorMessage}") 14 | .ToList(); 15 | 16 | return Task.FromResult(string.Join("\n", errors)); 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /src/Grpc.AspNetCore.FluentValidation/Internal/ServiceCollectionValidationProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using FluentValidation; 3 | using Microsoft.Extensions.DependencyInjection; 4 | 5 | namespace Grpc.AspNetCore.FluentValidation.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 | } 21 | } -------------------------------------------------------------------------------- /src/Grpc.AspNetCore.FluentValidation/Internal/TypeHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using FluentValidation; 4 | 5 | namespace Grpc.AspNetCore.FluentValidation.Internal 6 | { 7 | internal static class TypeHelper 8 | { 9 | public static Type GetServiceTypeFromValidatorType(Type type) 10 | { 11 | var validatorType = type.GetInterfaces() 12 | .FirstOrDefault(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IValidator<>)); 13 | 14 | if (validatorType == null) 15 | throw new AggregateException(type.Name + "is not implement with IValidator<>."); 16 | 17 | var messageType = validatorType.GetGenericArguments().First(); 18 | var serviceType = typeof(IValidator<>).MakeGenericType(messageType); 19 | 20 | return serviceType; 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /src/Grpc.AspNetCore.FluentValidation/Internal/ValidationInterceptor.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using FluentValidation; 3 | using Grpc.Core; 4 | using Grpc.Core.Interceptors; 5 | 6 | namespace Grpc.AspNetCore.FluentValidation.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 | 19 | public override async Task UnaryServerHandler( 20 | TRequest request, 21 | ServerCallContext context, 22 | UnaryServerMethod continuation) 23 | { 24 | await CheckRequestMessageAsync(request); 25 | return await continuation(request, context); 26 | } 27 | 28 | public override async Task ClientStreamingServerHandler(IAsyncStreamReader requestStream, ServerCallContext context, 29 | ClientStreamingServerMethod continuation) 30 | { 31 | await CheckRequestStreamAsync(requestStream); 32 | return await continuation(requestStream, context); 33 | } 34 | 35 | public override async Task ServerStreamingServerHandler(TRequest request, IServerStreamWriter responseStream, 36 | ServerCallContext context, ServerStreamingServerMethod continuation) 37 | { 38 | await CheckRequestMessageAsync(request); 39 | await continuation(request, responseStream, context); 40 | } 41 | 42 | public override async Task DuplexStreamingServerHandler(IAsyncStreamReader requestStream, 43 | IServerStreamWriter responseStream, ServerCallContext context, DuplexStreamingServerMethod continuation) 44 | { 45 | await CheckRequestStreamAsync(requestStream); 46 | await continuation(requestStream, responseStream, context); 47 | } 48 | 49 | private async Task CheckRequestMessageAsync(TRequest request) where TRequest : class 50 | { 51 | if (_locator.TryGetValidator(out var validator)) 52 | await ValidateAsync(request, validator); 53 | } 54 | 55 | private async Task CheckRequestStreamAsync(IAsyncStreamReader requestStream) where TRequest : class 56 | { 57 | if (_locator.TryGetValidator(out var validator)) 58 | { 59 | do 60 | { 61 | await ValidateAsync(requestStream.Current, validator); 62 | } while (await requestStream.MoveNext()); 63 | } 64 | } 65 | 66 | private async Task ValidateAsync(TRequest request, IValidator validator) 67 | { 68 | var results = await validator.ValidateAsync(request); 69 | if (!results.IsValid) 70 | { 71 | var message = await _handler.HandleAsync(results.Errors); 72 | throw new RpcException(new Status(StatusCode.InvalidArgument, message)); 73 | } 74 | } 75 | } 76 | } -------------------------------------------------------------------------------- /src/Grpc.AspNetCore.FluentValidation/ServiceCollectionHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using FluentValidation; 6 | using Grpc.AspNetCore.FluentValidation.Internal; 7 | using Microsoft.Extensions.DependencyInjection; 8 | using Microsoft.Extensions.DependencyInjection.Extensions; 9 | 10 | namespace Grpc.AspNetCore.FluentValidation 11 | { 12 | public static class ServiceCollectionHelper 13 | { 14 | private static void AddGrpcValidatorCore(IServiceCollection services) 15 | { 16 | services.TryAddScoped(provider => new ServiceCollectionValidationProvider(provider)); 17 | services.TryAddSingleton(); 18 | } 19 | 20 | /// 21 | /// Add custom message validator. 22 | /// 23 | /// service collection 24 | /// specific life time for validator 25 | /// custom validator type 26 | /// 27 | /// When try to register along validator class. 28 | public static IServiceCollection AddValidator(this IServiceCollection services, 29 | ServiceLifetime lifetime = ServiceLifetime.Scoped) where TValidator : class, IValidator 30 | { 31 | return AddValidator(services, typeof(TValidator), lifetime); 32 | } 33 | 34 | /// 35 | /// Add custom message validator. 36 | /// 37 | /// service collection 38 | /// specific life time for validator 39 | /// custom validator type 40 | /// 41 | public static IServiceCollection AddValidator(this IServiceCollection services, Type validatorType, 42 | ServiceLifetime lifetime = ServiceLifetime.Scoped) 43 | { 44 | AddGrpcValidatorCore(services); 45 | services.TryAdd(new ServiceDescriptor(TypeHelper.GetServiceTypeFromValidatorType(validatorType), validatorType, lifetime)); 46 | return services; 47 | } 48 | 49 | /// 50 | /// Add inline validator for simple rule. 51 | /// 52 | /// service collection 53 | /// configure validation rules 54 | /// grpc message type 55 | /// 56 | public static IServiceCollection AddInlineValidator(this IServiceCollection services, 57 | Action> validator) 58 | { 59 | AddGrpcValidatorCore(services); 60 | services.AddSingleton>(new InlineValidator(validator)); 61 | return services; 62 | } 63 | 64 | /// 65 | /// Add validator profile 66 | /// 67 | /// 68 | /// profile instance 69 | /// 70 | public static IServiceCollection AddValidatorProfile(this IServiceCollection services, ValidatorProfileBase profile) 71 | { 72 | AddGrpcValidatorCore(services); 73 | services.Add(profile.Validators); 74 | return services; 75 | } 76 | 77 | /// 78 | /// Add validator profile 79 | /// 80 | /// 81 | /// validator profile type 82 | /// 83 | public static IServiceCollection AddValidatorProfile(this IServiceCollection services) 84 | where TProfile : ValidatorProfileBase, new() 85 | { 86 | services.AddValidatorProfile(new TProfile()); 87 | return services; 88 | } 89 | 90 | /// 91 | /// Adds all validators from calling assembly 92 | /// 93 | /// The collection of services 94 | /// The lifetime of the validators. The default is transient 95 | /// Optional filter that allows certain types to be skipped from registration. 96 | /// 97 | public static IServiceCollection AddValidatorsFromAssemblies(this IServiceCollection services, 98 | ServiceLifetime lifetime = ServiceLifetime.Transient, 99 | Func filter = null) 100 | { 101 | return services.AddValidatorsFromAssembly(Assembly.GetCallingAssembly(), lifetime, filter); 102 | } 103 | 104 | /// 105 | /// Adds all validators in specified assemblies 106 | /// 107 | /// The collection of services 108 | /// The assemblies to scan 109 | /// The lifetime of the validators. The default is transient 110 | /// Optional filter that allows certain types to be skipped from registration. 111 | /// 112 | public static IServiceCollection AddValidatorsFromAssemblies(this IServiceCollection services, 113 | IEnumerable assemblies, 114 | ServiceLifetime lifetime = ServiceLifetime.Transient, 115 | Func filter = null) 116 | { 117 | foreach (var assembly in assemblies) 118 | services.AddValidatorsFromAssembly(assembly, lifetime, filter); 119 | return services; 120 | } 121 | 122 | /// 123 | /// Adds all validators in specified assembly 124 | /// 125 | /// The collection of services 126 | /// The assembly to scan 127 | /// The lifetime of the validators. The default is transient 128 | /// Optional filter that allows certain types to be skipped from registration. 129 | /// 130 | public static IServiceCollection AddValidatorsFromAssembly(this IServiceCollection services, 131 | Assembly assembly, 132 | ServiceLifetime lifetime = ServiceLifetime.Transient, 133 | Func filter = null) 134 | { 135 | foreach (var scanResult in AssemblyScanner.FindValidatorsInAssembly(assembly).Where(filter ?? (_ => true))) 136 | services.AddValidator(scanResult.ValidatorType); 137 | return services; 138 | } 139 | 140 | 141 | /// 142 | /// Add all profiles from calling assembly. 143 | /// 144 | /// The collection of services. 145 | /// 146 | public static IServiceCollection AddProfilesFromAssembly(this IServiceCollection services) 147 | { 148 | return services.AddProfilesFromAssembly(Assembly.GetCallingAssembly()); 149 | } 150 | 151 | /// 152 | /// Add all profiles from specific assembly. 153 | /// 154 | /// The collection of services. 155 | /// Assembly to find profiles. 156 | /// 157 | /// 158 | public static IServiceCollection AddProfilesFromAssembly(this IServiceCollection services, Assembly assembly) 159 | { 160 | foreach (var type in assembly.GetTypes().Where(type => type.IsClass && typeof(ValidatorProfileBase).IsAssignableFrom(type))) 161 | { 162 | if (type.GetConstructors().All(c => c.GetParameters().Length != 0)) 163 | throw new InvalidOperationException("All profile class should have constructor without any parameters."); 164 | 165 | services.AddValidatorProfile((ValidatorProfileBase) Activator.CreateInstance(type)); 166 | } 167 | 168 | return services; 169 | } 170 | } 171 | } -------------------------------------------------------------------------------- /src/Grpc.AspNetCore.FluentValidation/ValidatorProfileBase.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | using Microsoft.Extensions.DependencyInjection; 3 | 4 | namespace Grpc.AspNetCore.FluentValidation 5 | { 6 | /// 7 | /// Grpc validator profile for categorizing request validators 8 | /// 9 | public abstract class ValidatorProfileBase 10 | { 11 | internal IServiceCollection Validators { get; } = new ServiceCollection(); 12 | 13 | /// 14 | /// Add inline request validator 15 | /// 16 | /// GRPC request type 17 | /// 18 | protected AbstractValidator CreateInlineValidator() 19 | { 20 | var validator = new InlineValidator(); 21 | Validators.AddSingleton>(validator); 22 | return validator; 23 | } 24 | 25 | /// 26 | /// Add validator type 27 | /// 28 | /// 29 | protected void AddValidator() where TValidator : class, IValidator 30 | { 31 | AddValidator(ServiceLifetime.Scoped); 32 | } 33 | 34 | /// 35 | /// Add validator type 36 | /// 37 | /// 38 | /// 39 | protected void AddValidator(ServiceLifetime lifetime) where TValidator : class, IValidator 40 | { 41 | Validators.AddValidator(lifetime); 42 | } 43 | } 44 | } --------------------------------------------------------------------------------