2

I'm using FluentValidation 11.5.1. I don't want to use:

// MapPost //
public static void AddUser([FromBody] UserRequest, [FromServices] IValidator<UserRequest> validator)

I want it to be automatic:

public static void AddUser([FromBody] UserRequest)
{
 If it will fail, it would show the errors and wouldn't get here,
 Without to injecting the validator.
}

in Program.cs, I have used:

services.AddMvc().AddFluentValidation() - it's deprecated and minimal api is not mvc.

And it didn't work.

  • How the validator can validate automatically the request without injecting the validator?
  • Request from client side -> EndPoint: AddUser([FromBody] UserRequest) -> Incase it will not pass the validation you will get an errors from FluentValidation without "[FromServices] IValidator validator" injecting the validator in the endpoint, kinda like in Data Annotations.
Guru Stron
  • 102,774
  • 10
  • 95
  • 132

1 Answers1

3

There is nothing build-in at the moment, as far as I know. You can look into some 3rd party libraries like O9d.AspNet.FluentValidation which contains validation filter to support fluent validation.

Another options:

  1. Write your own validation filter like in this answer. To get you started:
public class ValidationFilter<T> : IEndpointFilter where T : class
{
    private readonly IValidator<T> _validator;

    public ValidationFilter(IValidator<T> validator)
    {
        _validator = validator;
    }

    public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
    {
        var obj = context.Arguments.FirstOrDefault(x => x?.GetType() == typeof(T)) as T;

        if (obj is null)
        {
            return Results.BadRequest();
        }

        var validationResult = await _validator.ValidateAsync(obj);

        if (!validationResult.IsValid)
        {
            return Results.BadRequest(string.Join("/n", validationResult.Errors));
        }

        return await next(context);
    }
}

// and usage 
app.MapPost("api/user", (Example e) =>  e)
    .AddEndpointFilter<ValidationFilter<Example>>();
  1. Leverage binding mechanism (for example) by creating wrapper which will parse the incoming json and perform validation.
Guru Stron
  • 102,774
  • 10
  • 95
  • 132