[英]FluentValidation client side validation not working for inherited class
[英]FluentValidation automatic validation not working
我在我的 .net 核心 web api 項目中使用流利驗證。 但它不是自動添加的,我哪里會犯錯誤。 ?
.net 核心 7.0 FluentValidation.AspNetCore 11.2.2
builder.Services.AddControllers(options =>
{
options.Filters.Add(new ValidateFilterAttribute());
});
builder.Services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddFluentValidationAutoValidation();
builder.Services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly());
CompanyUpdateDtoValidator.cs 文件的內容
public class CompanyUpdateDtoValidator : AbstractValidator<CompanyUpdateDto>
{
public CompanyUpdateDtoValidator()
{
RuleFor(x => x.Id).NotNull().WithMessage("{PropertyName} This field is required..").NotEmpty().WithMessage("{PropertyName} This field is required..");
RuleFor(x => x.Name).NotNull().WithMessage("{PropertyName} This field is required.").NotEmpty().WithMessage("{PropertyName} This field is required..");
RuleFor(x => x.BusinessCode).NotNull().WithMessage("{PropertyName} This field is required..").NotEmpty().WithMessage("{PropertyName} This field is required..");
}
}
FluentValidation 做了如下改動。 https://github.com/FluentValidation/FluentValidation/issues/1965
ValidateFilterAttribuate 的內容
public class ValidateFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
var errors = context.ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage).ToList();
context.Result = new BadRequestObjectResult(CustomResponseDto<NoContent>.Fail(400, errors));
}
}
}
但是我發送了一個丟失的 json,如下所示,但是沒有返回 fluentvalidation 給我。
{
"id": 0,
"name": "Test 123"
}
此字段“BusinessCode”是必需的但缺少,我將其發送以進行測試,但它不會給出返回錯誤
我找不到我哪里做錯了
在你的代碼中你有:
builder.Services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly());
這假設您的驗證器與Program.cs
在同一個程序集中,但情況可能並非如此。
如果您所有的驗證器都在同一個程序集中,您可以使用:
builder.Services.AddValidatorsFromAssemblyContaining<CompanyUpdateDtoValidator>();
如果它們不在同一個程序集中,您將必須使用上述代碼行為每個程序集注冊一個驗證器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.