Use FluentValidation rules instead ComponentModel attributes to define swagger schema.
Note: For AspNetCore see: https://github.com/micro-elements/MicroElements.Swashbuckle.FluentValidation
- Swashbuckle
- FluentValidation
- FluentValidation.WebApi
- MicroElements.Swashbuckle.FluentValidation.WebApi
After you add Swashbuckle package you can find generated SwaggerConfig.cs
- Comment [assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")] (we need to register swagger after FluentValidation in WebApiConfig)
- Add registration c.AddFluentValidationRules();
// Commented because we need manual registration in right order
//[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]
public class SwaggerConfig
{
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
...
// Adds FluentValidationRules to swagger
c.AddFluentValidationRules();
...
}
...
- Add
FluentValidationModelValidatorProvider.Configure(config);
- Add
SwaggerConfig.Register();
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Adds Fluent validation to WebApi
FluentValidationModelValidatorProvider.Configure(config);
// Registers swagger for WebApi
SwaggerConfig.Register();
}
}
See sample project: https://github.com/micro-elements/MicroElements.Swashbuckle.FluentValidation.WebApi/tree/master/src/AspNetWebApiOld
Initial version of this project was based on Mujahid Daud Khan answer on StackOwerflow: https://stackoverflow.com/questions/44638195/fluent-validation-with-swagger-in-asp-net-core/49477995#49477995