zymlabs / nswag-fluentvalidation

Use FluentValidation rules instead of ComponentModel attributes to define swagger schema.
MIT License
60 stars 13 forks source link

Doesn't generate validation schema #12

Open mustafamagdy opened 2 years ago

mustafamagdy commented 2 years ago

I followed the same steps to configure the Schema Processor and the generated schema is a generic one not the correct schema:

using FluentValidation;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Mvc;
using ZymLabs.NSwag.FluentValidation;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOpenApiDocument((document, sp) =>
{
  var fluentValidationSchemaProcessor = sp.CreateScope().ServiceProvider.GetService<FluentValidationSchemaProcessor>();
  document.SchemaProcessors.Add(fluentValidationSchemaProcessor);
});

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddFluentValidationAutoValidation();

builder.Services.AddScoped(sp =>
{
  var validationRules = sp.GetService<IEnumerable<FluentValidationRule>>();
  var loggerFactory = sp.GetService<ILoggerFactory>();

  return new FluentValidationSchemaProcessor(sp, validationRules, loggerFactory);
});

var app = builder.Build();

app.UseOpenApi();
app.UseSwaggerUi3();
app.UseReDoc();

app.MapGet("/", () => "Hello World!");
app.MapPost("/", [ProducesResponseType(400, Type = typeof(HttpValidationProblemDetails))](CarMode car) => $"Hello {car.Model}");

app.Run();

public class CarMode
{
  public string Model { get; set; }
}

public class CarValidator : AbstractValidator<CarMode>
{
  public CarValidator()
  {
    RuleFor(a => a.Model)
      .NotEmpty().WithMessage("Model should not be empty");
  }
}

Here is the output:

Screen Shot 2022-08-19 at 3 58 49 PM