Trying to get MicroElements.Swashbuckle.FluentValidation to work using the Command Handler pattern from https://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/microservice-application-layer-implementation-web-api
Using ASP .Net Core 2.2 MicroElements.Swashbuckle.FluentValidation v3.0.0-alpha.1 (as an assembly not a package ref) Swashbuckle.AspNetCore 5.0.0-rc2
I have this is Startup.cs
return services.AddSwaggerGen(setup =>
{
setup.AddFluentValidationRules();
});
using fluent Validation
This does not extract the Fluent validations into schema for the request body object.
public class AddModelsCommandValidator : AbstractValidator<AddModelsCommand>
{
public AddModelsCommandValidator()
{
//1. validate request
RuleFor(e => e.Model).InvalidRequestValidation();
When(x => x.Model != null, () =>
{
//2. validate request body
RuleFor(e => e.Model.ModelCode).StringRequiredValidation();
RuleFor(e => e.Model.ModelCode).StringMaxLengthValidation(5);
RuleFor(e => e.Model.ProgramName).StringRequiredValidation();
RuleFor(e => e.Model.ProgramName).StringMaxLengthValidation(50);
});
}
}
public class AddModelsCommand : IRequest<AddModelsCommandResult>
{
public Model Model { get; }
public AddModelsCommand(Model model)
{
Model = model;
}
}
public class Model
{
/// <summary>
/// Unique code of the Model
/// </summary>
public string ModelCode { get; set; }
/// <summary>
/// The name of the Program
/// </summary>
public string ProgramName { get; set; }
}
The following code does extract the Fluent validations into schema for the request body object. (because 1. the AbstractValidator is on the Model not the Command, and 2. I have removed the conditional When() validation)
public class AddModelsCommandValidator : AbstractValidator<Model>
{
public AddModelsCommandValidator()
{
//2. validate request body
RuleFor(e => e.ModelCode).StringRequiredValidation();
RuleFor(e => e.ModelCode).StringMaxLengthValidation(5);
RuleFor(e => e.ProgramName).StringRequiredValidation();
RuleFor(e => e.ProgramName).StringMaxLengthValidation(50);
}
}
Is there way to call AddFluentValidationRules and also use the Command Handler pattern?
The issue here is AbstractValidator<Model> has to be used..
AbstractValidator<Command> does not really make sense
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With