我目前对我的Web api使用< code>Fluent Validation而不是< code>Data Annotations,并对api文档使用swagger。流畅验证规则没有反映在swagger模型中,因为我无法使用swagger模式过滤器配置流畅验证规则。
这个博客有一个很好的解释,它与ASP.netMVC.
到目前为止,我已经尝试了以下代码,但我无法获得验证器类型。
services.AddSwaggerGen(options => options.SchemaFilter<AddFluentValidationRules>());
public class AddFluentValidationRules : ISchemaFilter
{
public void Apply(Schema model, SchemaFilterContext context)
{
model.Required = new List<string>();
var validator = GetValidator(type); // How?
var validatorDescriptor = validator.CreateDescriptor();
foreach (var key in model.Properties.Keys)
{
foreach (var propertyValidator in validatorDescriptor.GetValidatorsForMember(key))
{
// Add to model properties as in blog
}
}
}
}
> < li>
安装Nuget包:< code >微量元素。swash buckle . fluent validation
添加到configure services:< code > services。AddFluentValidationRulesToSwagger();
经过搜索,我终于发现我需要验证工厂
的验证器实例。
public class AddFluentValidationRules : ISchemaFilter
{
private readonly IValidatorFactory _factory;
/// <summary>
/// Default constructor with DI
/// </summary>
/// <param name="factory"></param>
public AddFluentValidationRules(IValidatorFactory factory)
{
_factory = factory;
}
/// <summary>
/// </summary>
/// <param name="model"></param>
/// <param name="context"></param>
public void Apply(Schema model, SchemaFilterContext context)
{
// use IoC or FluentValidatorFactory to get AbstractValidator<T> instance
var validator = _factory.GetValidator(context.SystemType);
if (validator == null) return;
if (model.Required == null)
model.Required = new List<string>();
var validatorDescriptor = validator.CreateDescriptor();
foreach (var key in model.Properties.Keys)
{
foreach (var propertyValidator in validatorDescriptor
.GetValidatorsForMember(ToPascalCase(key)))
{
if (propertyValidator is NotNullValidator
|| propertyValidator is NotEmptyValidator)
model.Required.Add(key);
if (propertyValidator is LengthValidator lengthValidator)
{
if (lengthValidator.Max > 0)
model.Properties[key].MaxLength = lengthValidator.Max;
model.Properties[key].MinLength = lengthValidator.Min;
}
if (propertyValidator is RegularExpressionValidator expressionValidator)
model.Properties[key].Pattern = expressionValidator.Expression;
// Add more validation properties here;
}
}
}
/// <summary>
/// To convert case as swagger may be using lower camel case
/// </summary>
/// <param name="inputString"></param>
/// <returns></returns>
private static string ToPascalCase(string inputString)
{
// If there are 0 or 1 characters, just return the string.
if (inputString == null) return null;
if (inputString.Length < 2) return inputString.ToUpper();
return inputString.Substring(0, 1).ToUpper() + inputString.Substring(1);
}
}
并将此类添加到swaggerGen选项
options.SchemaFilter<AddFluentValidationRules>();
我根据圣战者达乌德汗的答案创建了github项目和nuget包。我进行了重新设计以支持可扩展性并支持其他验证器。
github: https://github.com/micro-elements/MicroElements.Swashbuckle.FluentValidation
Nuget:https://www.nuget.org/packages/MicroElements.Swashbuckle.FluentValidation
注意:有关网络数据,请参见:https://github.com/micro-elements/MicroElements.Swashbuckle.FluentValidation.WebApi
<PackageReference Include="FluentValidation.AspNetCore" Version="7.5.2" />
<PackageReference Include="MicroElements.Swashbuckle.FluentValidation" Version="0.4.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="2.3.0" />
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services
.AddMvc()
// Adds fluent validators to Asp.net
.AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<CustomerValidator>());
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
// Adds fluent validation rules to swagger
c.AddFluentValidationRules();
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app
.UseMvc()
// Adds swagger
.UseSwagger();
// Adds swagger UI
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
}
public class Sample
{
public string PropertyWithNoRules { get; set; }
public string NotNull { get; set; }
public string NotEmpty { get; set; }
public string EmailAddress { get; set; }
public string RegexField { get; set; }
public int ValueInRange { get; set; }
public int ValueInRangeExclusive { get; set; }
}
public class SampleValidator : AbstractValidator<Sample>
{
public SampleValidator()
{
RuleFor(sample => sample.NotNull).NotNull();
RuleFor(sample => sample.NotEmpty).NotEmpty();
RuleFor(sample => sample.EmailAddress).EmailAddress();
RuleFor(sample => sample.RegexField).Matches(@"(\d{4})-(\d{2})-(\d{2})");
RuleFor(sample => sample.ValueInRange).GreaterThanOrEqualTo(5).LessThanOrEqualTo(10);
RuleFor(sample => sample.ValueInRangeExclusive).GreaterThan(5).LessThan(10);
}
}
请随意添加问题!
.NET核心和ASP.NET核心到底有什么区别?
当从查询字符串提取的模型将字典作为其属性之一时,Swagger生成错误的URL。如何告诉Swagger更改URL中字典的格式或手动定义输入参数模式,而不自动生成?试图使用Swashbuck和NSwag。 控制器 输入模型-查询字符串 Swagger UI为查询模型的“条件”属性显示了这种格式 Swagger生成的URL-Open API v2-将不会绑定到“条件” Swagger生成的URL-Op
凭据正确。5.7.57 SMTP-客户端未通过身份验证以发送邮件,535 5.7.139身份验证不成功 在中使用SMTP发送电子邮件时返回此错误。网 此应用程序部署在Azure中不确定是什么导致了问题,之前它正在工作,突然停止了。 已尝试使用交换服务器抛出401未授权错误。
知道如何正确设置控制器描述吗? 谢谢,马里奥