如何在.netcore 6 razor页面中使用FormHelper和FluentValidation

kye*_*nry 5 c# razor asp.net-core asp.net-core-6.0

我正在从 mvc 转向 razor 页面,但似乎无法找到使用 Fluent 验证器和 FormHelper 进行验证的方法。

一般采用mvc模式

[FormValidator]
Public async Task<IActionResult> submitFormAction()
{
    // do something 
    return View();
}
Run Code Online (Sandbox Code Playgroud)

带 Razor 页面

 public class AddModel : PageModel
 {
     public void OnGet()
     {

     }
 
     // 'FormValidator' cannot be applied to razor page handler
     // method it may be applied to either Razor page model or
     // applied globally
     [FormValidator]
     public async Task OnPostAsync()
     {
         
     }
 }
Run Code Online (Sandbox Code Playgroud)

kye*_*nry 2

对于面临同样问题的其他人。

问题在于,在以前的版本 .netcore 中,您可以简单地FluentValidation注册服务FluentValidation

service.AddFluentValidation(config => config.RegisterValidatorsFromAssemblyContaining<StartUp>());
Run Code Online (Sandbox Code Playgroud)

上面的代码.netcore使用反射来注册StartUp.cs继承的程序集中的所有类AbstractValidator<T>

但对于 .netcore 6,我仍然必须使用上面的代码,但将其替换StartupProgram.netcore 6 不使用StartUp.cs,并且仍然必须隐式注册验证服务

builder.Services.AddTransient<IValidator<SomeClass>, SomeClassValidator>();
Run Code Online (Sandbox Code Playgroud)

这对我有用,但我感觉它可以进一步简化,因为如果我正在开发一个大型应用程序并且我有多达 20 个验证器,我Program.cs将无法维护

PS:[FormValidator]操作方法已过时,因为使用asp-FormHelper="true"标签助手是可以的