Razor 页面流利验证服务器端不工作

Razor pages fluent validation server side not working

我使用流利验证来验证我的表单。 我使用 asp.net 核心(剃须刀页面)。 它在客户端正常工作,但是当我删除 jquery 验证脚本以测试服务器端验证时,我发现它不起作用并且 ModelState 为真。 我该如何解决这个问题。有什么解决办法吗?

这是页面模型属性

/// <summary>
    /// Gets or sets the user role name
    /// </summary>
    [HamiResourceDisplayName("Security.Role.Fields.Name")]
    [BindProperty]
    public string Name { get; set; }

    /// <summary>
    /// Gets or sets the user role system name
    /// </summary>
    [HamiResourceDisplayName("Security.Role.Fields.SystemName")]
    [BindProperty]
    [PageRemote(
        //ErrorMessage = "Already exists",
        AdditionalFields = "__RequestVerificationToken",
        HttpMethod = "Post",
        PageHandler = "CheckSystemName"
    )]
    public string SystemName { get; set; }

    /// <summary>
    /// Gets or sets a value indicate whether the user role is for managers
    /// </summary>
    [HamiResourceDisplayName("Security.Role.Fields.ManagerRole")]
    [BindProperty]
    public bool IsManagerRole { get; set; }

    /// <summary>
    /// Gets or sets a value indicating whether the level of manager if it's a manager role
    /// </summary>
    [HamiResourceDisplayName("Security.Role.Fields.ManagerLevel")]
    [BindProperty]
    public int? ManagerLevel { get; set; }

这是 OnPost

    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid) return Page();
        var role = new Role()
        {
            Name = Name,
            Inactive = false,
            IsSystemRole = false,
            SystemName = SystemName,
            IsManagerRole = IsManagerRole,
            ManagerLevel = IsManagerRole ? ManagerLevel : null
        };
        await _userService.InsertRoleAsync(role);
        return RedirectToPage("/Security/Roles/Index");
    }

最后这是我的验证

public class CreateRolesValidator : AbstractValidator<CreateModel>
{
    public CreateRolesValidator(ILocalizationService localizationService)
    {
        RuleFor(x => x.Name).NotNull().WithMessageAwait(localizationService.GetResourceAsync("Security.Role.Fields.Name.Required"));
        RuleFor(x => x.SystemName).NotNull().WithMessageAwait(localizationService.GetResourceAsync("Security.Role.Fields.SystemName.Required"));
        //RuleFor(x => x.SystemName).IsUniqueRoleSystemName().WithMessageAwait(localizationService.GetResourceAsync("Security.Role.SystemName.SystemNameAlreadyExists"));
        RuleFor(x => x.ManagerLevel).NotNull().DependentRules(() =>
        {
            RuleFor(x => x.IsManagerRole).Must(x => x.Equals(true));
        }).WithMessageAwait(localizationService.GetResourceAsync("Security.Role.Fields.ManagerLevel.Required"));
    }
}

例如,“名称”的 NotEmpty() 在客户端可以正常工作,但在服务器端不能正常工作,并且不会被捕获为无效模型状态。

尝试创建一个单独的 class 来存储模型属性,然后为其添加验证并在 razor 页面中使用它。

例如:创建一个RoleViewModel:

public class RoleViewModel
{
    /// <summary>
    /// Gets or sets the user role name
    /// </summary> 
    [BindProperty]
    public string Name { get; set; }

    /// <summary>
    /// Gets or sets the user role system name
    /// </summary> 
    [BindProperty]
    [PageRemote(
        //ErrorMessage = "Already exists",
        AdditionalFields = "__RequestVerificationToken",
        HttpMethod = "Post",
        PageHandler = "CheckSystemName"
    )]
    public string SystemName { get; set; }

    /// <summary>
    /// Gets or sets a value indicate whether the user role is for managers
    /// </summary> 
    [BindProperty]
    public bool IsManagerRole { get; set; }

    /// <summary>
    /// Gets or sets a value indicating whether the level of manager if it's a manager role
    /// </summary> 
    [BindProperty]
    public int? ManagerLevel { get; set; }
}
public class CreateRolesValidator : AbstractValidator<RoleViewModel>
{
    public CreateRolesValidator()
    {
        RuleFor(x => x.Name).NotNull();
        RuleFor(x => x.SystemName).NotNull();
        //RuleFor(x => x.SystemName).IsUniqueRoleSystemName().WithMessageAwait(localizationService.GetResourceAsync("Security.Role.SystemName.SystemNameAlreadyExists"));
        RuleFor(x => x.ManagerLevel).NotNull().DependentRules(() =>
        {
            RuleFor(x => x.IsManagerRole).Must(x => x.Equals(true));
        });
    }
}

然后,在ConfigureServices方法中注册验证服务:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages().AddFluentValidation();

        services.AddTransient<IValidator<RoleViewModel>, CreateRolesValidator>();
    }

然后在 Create.cshtml.cs 文件中:

public class CreateModel : PageModel
{
    [BindProperty]
    public RoleViewModel Role { get; set; }
    public void OnGet()
    {
    }
    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid) return Page();
       
        return RedirectToPage("/Index");
    }
}

和Create.cshtml:已禁用客户端验证

@page
@model RazorWebApplication.Pages.CreateModel

<form method="post">

    Name: <input asp-for="Role.Name" class="form-control" /> <span asp-validation-for="Role.Name" class="text-danger"></span>
    <br />
    SystemName: <input asp-for="Role.SystemName" class="form-control" /> <span asp-validation-for="Role.SystemName" class="text-danger"></span>
    <br />
    IsManagerRole: <input asp-for="Role.IsManagerRole" class="form-control" /> <span asp-validation-for="Role.IsManagerRole" class="text-danger"></span>
    <br />
    ManagerLevel: <input asp-for="Role.ManagerLevel" class="form-control" /> <span asp-validation-for="Role.ManagerLevel" class="text-danger"></span>

    <br /><br />
    <input type="submit" value="submtit" />
</form>

@*@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}*@

结果如下: