在 ASP.NET Core-6 Web API 中,我使用的是 FluentValidation.AspNetCore(11.2.1)。
我在 Program.cs 中有这段代码:
builder.Services.AddMvc().AddFluentValidation(fv => {
fv.DisableDataAnnotationsValidation = true;
fv.RegisterValidatorsFromAssembly(typeof(Program).Assembly);
fv.RegisterValidatorsFromAssembly(Assembly.GetExecutingAssembly());
fv.ImplicitlyValidateChildProperties = true;
fv.ImplicitlyValidateRootCollectionElements = true;
fv.AutomaticValidationEnabled = true;
});
但是我遇到了这个错误,上面的所有代码都突出显示了:
FluentValidationMvcExtensions.AddFluentValidation(IMvcBuilder, Action)' 已过时:'不推荐调用 AddFluentValidation()
如何解决这个问题?
谢谢
添加以下方法以实现流畅的自动验证。这也将修复过时的警告
builder.Services.AddFluentValidationAutoValidation();
builder.Services.AddFluentValidationClientsideAdapters();
builder.Services.AddValidatorsFromAssembly(typeof(SignUpRequestModelValidator).Assembly);
根据文档(https://docs.fluidation.net/en/latest/aspnet.html),不建议使用自动验证。
因此,我建议不要使用自动验证并删除 AddMvc(),因为自动验证可与 AddMvc 配合使用,https://github.com/FluentValidation/FluentValidation/issues/1377
现在让我们来解决您的问题,假设您使用的是.net6,以下代码应该可以工作。
using FluentValidation.AspNetCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddFluentValidation(conf =>
{
conf.RegisterValidatorsFromAssembly(typeof(Program).Assembly);
conf.AutomaticValidationEnabled = false;
});
我也遇到类似的错误。
尝试安装 FluentValation.AspNetCore 包 11.1.2 及以下版本。
错误已解决。
希望它对你有用
我们可以通过以下 URL 查看 FluentValidation 的文档:https://github.com/FluentValidation/FluentValidation/issues/1965
例如:
// Before
services.AddFluentValidation(options => {
options.RegisterValidatorsFromAssemblyContaining<MyValidator>();
});
// After migration:
services.AddFluentValidationAutoValidation();
services.AddFluentValidationClientsideAdapters();
services.AddValidatorsFromAssemblyComtaining<MyValidator>();
// Before: Enabling auto-validation and disabling clientside validation
services.AddFluentValidation(config =>
{
config.ConfigureClientsideValidation(enabled: false);
});
// After: Enabling auto-validation only
services.AddFluentValidationAutoValidation();
// Before: Disabling auto-validation and leaving clientside validation enabled:
services.AddFluentValidation(config =>
{
config.AutomaticValidationEnabled = false;
});
// After: Enabling client validation only:
services.AddFluentValidationClientsideAdapters();
通过将 FluentValidation.AspNetCore 包 11.0.0 安装到项目中解决了该错误