1

We have a number of web api services that currently use FluentValidation and SharpGrip.FluentValidation.AutoValidation for automatic asynchronous validation. It works really well.

At present the services are only used by one type of user but we're about to support users with different roles who, for some requests, will require different validation rules.

Having read the docs for FluentValidation, it seems that Rulesets would be an elegant solution to this problem. We could introduce a ruleset per role, and use the Default Ruleset for common rules. Then, we could evaluate the HttpContext.User to determine which roles/rulesets to use.

Has anyone used this approach before? How can we customize which rulesets are evaluated when using SharpGrip.FluentValidation.AutoValidation?

Thanks

1 Answer 1

1

So, after further reading of SharpGrip.FluentValidation.AutoValidation, I came across the IGlobalValidationInterceptor.

As per the docs

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

However, for my use case, it appears perfect:

public class ValidationInterceptor : IGlobalValidationInterceptor
{
    public IValidationContext? BeforeValidation(ActionExecutingContext actionExecutingContext, IValidationContext validationContext)
    {
        if (actionExecutingContext.HttpContext.User.IsInRole(Roles.Users))
        {
            return ValidationContext<object>.CreateWithOptions(validationContext.InstanceToValidate, options =>
            {
                options.IncludeRuleSets(Roles.Users).IncludeRulesNotInRuleSet();
            });
        }
        if (actionExecutingContext.HttpContext.User.IsInRole(Roles.Employees))
        {
            return ValidationContext<object>.CreateWithOptions(validationContext.InstanceToValidate, options =>
            {
                options.IncludeRuleSets(Roles.Employees).IncludeRulesNotInRuleSet();
            });
        }
        
        return validationContext;
    }

    public ValidationResult? AfterValidation(ActionExecutingContext actionExecutingContext,
        IValidationContext validationContext)
    {
        return null;
    }
}

Thanks to the contributors at SharpGrip

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.