Git Product home page Git Product logo

grpc-dotnet-validator's Introduction

grpc-dotnet-validator

Request message validator middleware for Grpc.AspNetCore

Nuget

Feature

  • Support async validation for unary, streaming call
  • Support IoC LifeStyle scopes and dependency injection
  • Profile for validators
  • Scan validators and profiles from assembly

How to use.

This package is integrated with Fluent Validation. If you want to know how build your own validation rules, please checkout Fluent Validation Docs

Add custom message validator

// Write own message validator
public class HelloRequestValidator : AbstractValidator<HelloRequest>
{
    public HelloRequestValidator()
    {
        RuleFor(request => request.Name).NotEmpty();
    }
}

public class Startup
{
    // ...
    public void ConfigureServices(IServiceCollection services)
    {
        // 1. Enable message validation feature.
        services.AddGrpc(options => options.EnableMessageValidation());

        // 2. Add custom validators for messages, default scope is scope.
        services.AddValidator(typeof(HelloRequestValidator));
        services.AddValidator<HelloRequestValidator>();
        services.AddValidator<HelloRequestValidator>(LifeStyle.Singleton);
    }
    // ...
}

Then, If the message is invalid, Grpc Validator return with InvalidArgument code and empty message object.

Add inline custom validator

if you don't want to create many validation class for simple validation rule in your project, you just use below inline validator feature like below example.

Note that, Inline validator always be registered singleton in your service collection. Because, There are no way for using other dependency.

public class Startup
{
    // ...
    public void ConfigureServices(IServiceCollection services)
    {
        // 1. Enable message validation feature.
        services.AddGrpc(options => options.EnableMessageValidation());

        // 2. Add inline validators for messages, scope is always singleton
        services.AddInlineValidator<HelloRequest>(rules => rules.RuleFor(request => request.Name).NotEmpty());
    }
    // ...
}

Profiling validators

If you don't want to make a mess your startup class by registering validators, you implement validator profile and use it.

public class SampleProfile : ValidatorProfileBase
{
    public SampleProfile()
    {
        CreateInlineValidator<SampleRequest>()
            .RuleFor(r => r.Data).NotNull().NotEmpty()
            .RuleFor(r => r.Name).NotNull();
        AddValidator<SampleRequestValidator>();
        AddValidator<SampleRequestValidator>(ServiceLifetime.Singleton);
    }
}

// Then in your Startup class
public void ConfigureServices(IServiceCollection services)
{
    services.AddGrpc(options => options.EnableMessageValidation());
    services.AddValidatorProfile<SampleProfile>();
}

Scan and register profiles/validators from assembly.

// Place somewhere validator or profile class.
public class HelloRequestValidator : AbstractValidator<HelloRequest>
{
    public HelloRequestValidator()
    {
        RuleFor(request => request.Name).NotEmpty();
    }
}

public class SampleProfile : ValidatorProfileBase
{
    public SampleProfile()
    {
        CreateInlineValidator<SampleRequest>()
            .RuleFor(r => r.Data).NotNull().NotEmpty()
            .RuleFor(r => r.Name).NotNull();
        AddValidator<SampleRequestValidator>();
        AddValidator<SampleRequestValidator>(ServiceLifetime.Singleton);
    }
}

// Then in your Startup class
public void ConfigureServices(IServiceCollection services)
{
    services.AddGrpc(options => options.EnableMessageValidation());

    // Scan profile and validators from calling assembly.
    services.AddValidatorsFromAssemblies(); 
    services.AddProfilesFromAssembly();

    // Scan profiles and validators from specific assembly.
    services.AddValidatorsFromAssemblies(typeof(InternalLibarary).Assembly); 
    services.AddProfilesFromAssembly(typeof(InternalLibarary).Assembly);
}

Customize validation failure message.

If you want to custom validation message handler for using your own error message system, Just implement IValidatorErrorMessageHandler and put it service collection.

public class CustomMessageHandler : IValidatorErrorMessageHandler
{
    public Task<string> HandleAsync(IList<ValidationFailure> failures)
    {
        return Task.FromResult("Validation Error!");
    }
}

public class Startup
{
    // ...
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddGrpc(options => options.EnableMessageValidation());

        // Just put at service collection your own custom message handler that implement IValidatorErrorMessageHnadler.
        // This should be placed before calling AddInlineValidator() or AddValidator();
        services.AddSingleton<IValidatorErrorMessageHanlder>(new CustomMessageHandler())
        services.AddInlineValidator<HelloRequest>(rules => rules.RuleFor(request => request.Name).NotEmpty());
    }
    // ...
}

How to test my validation

If you want to write integration tests. This test sample may help you.

Versioning

This pakage`s versioning is following version of Grpc.AspNetCore

grpc-dotnet-validator's People

Contributors

enif-lee avatar nmakhmutov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

grpc-dotnet-validator's Issues

Add validators from assemblies

In fluentvalidation you can add many validators just from assemblies. It's realy useful when you have a lot of validators in you project.

For instance:

var assemblies = AppDomain.CurrentDomain.GetAssemblies();
services.AddValidatorsFromAssemblies(assemblies);

And then all you classes inherits from AbstractValidator<T> should be added as validator in you project.
Please, could you add this functionality in your project?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.