【问题标题】:ASP.NET Core Web API - Fluent Validation not working as expectedASP.NET Core Web API - Fluent Validation 未按预期工作
【发布时间】:2022-07-08 21:00:58
【问题描述】:

我正在为 ASP.NET Core-6 Web API 中的用户注册实现 Fluent Validation。这些是我的代码

应用用户:

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string MobileNumber { get; set; }

    [DefaultValue(false)]
    public bool? IsAdmin { get; set; }
}

然后我有 DTO:

public class AdminCreateDto
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
    public string MobileNumber { get; set; }
    public string Password { get; set; }
}

public class AdminUserDto
{
    public string Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string UserName { get; set; }
    public bool? IsAdmin { get; set; }
    public string MobileNumber { get; set; }
}

我通过如下所示的 DTO 验证了模型中的字段:

public class LoginRequestDtoValidator : AbstractValidator<LoginRequestDto>
{
    public LoginRequestDtoValidator()
    {
        RuleFor(user => user.UserName)
            .NotNull()
            .NotEmpty().WithMessage("Username field is required.");

        RuleFor(user => user.Password)
            .NotNull()
            .NotEmpty().WithMessage("Password field is required.");
    }
}

Fluent 验证器注入:

services.AddTransient<IValidator<LoginRequestDto>, LoginRequestDtoValidator>();

然后是服务。接口和实现。

public interface IAdminUserService
{
    Task<Response<AdminUserDto>> CreateAdminUserAsync(AdminCreateDto adminDto);
}

public async Task<Response<AdminUserDto>> CreateAdminUserAsync(AdminCreateDto model)
{
    var existingUser = await _userManager.FindByNameAsync(model.UserName);
    var response = new Response<AdminUserDto>();
    using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
    {
        if (existingUser == null)
        {
            var user = _mapper.Map<ApplicationUser>(model);
            user.IsAdmin = true;
            var result = await _userManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await _userManager.AddToRoleAsync(user, UserRoles.Admin);
                    transaction.Complete();
                    return response;
            }
        }
        else
        {
            _logger.Information("Admin User Registration failed");
            return response;
        }
        transaction.Complete();
        return response;
    }
}

最后是控制器:

[HttpPost]
[Route(register)]
public async Task<ActionResult<Response<AdminUserDto>>> CreateAdminUserAsync([FromBody] AdminCreateDto model)
{
    _logger.LogInformation($"Registration Attempt for {model.UserName}");
    var result = await _adminUserService.CreateAdminUserAsync(model);
    return StatusCode(result.StatusCode, result);
}

程序.cs:

var builder = WebApplication.CreateBuilder(args);
ConfigurationManager configuration = builder.Configuration;
var environment = builder.Environment;

builder.Services.AddHttpContextAccessor();
builder.Services.AddHttpClient();

builder.Services.AddControllers()
                .AddFluentValidation(options =>
                {
                    // Validate child properties and root collection elements
                    options.ImplicitlyValidateChildProperties = true;
                    options.ImplicitlyValidateRootCollectionElements = true;
                    options.RegisterValidatorsFromAssembly(Assembly.GetExecutingAssembly());
                    options.AutomaticValidationEnabled = true;
                });

// Configure AutoMapper
builder.Services.ConfigureAutoMappers();
builder.Services.AddDependencyInjection();

var app = builder.Build();

app.MapControllers();
app.Run();

当我没有在用户名和密码字段中输入任何内容时,验证器中的自定义消息不会显示。它假设显示消息以通知用户验证问题。

我哪里弄错了?

谢谢

【问题讨论】:

    标签: c# asp.net-web-api fluentvalidation


    【解决方案1】:

    我猜你忘了注册你的验证类...

    不知道你用的是什么AddControllers、AddControllersWithViews之类的……,你可以搞定的。

     services.AddControllersWithViews()
       .AddFluentValidation(fv => {
        fv.RegisterValidatorsFromAssemblyContaining<LoginRequestDtoValidator >();
       }
                                   
    

    【讨论】:

    • 我做了配置。因为它是Web API。我做了 AddMvc。查看代码中的Program.cs
    猜你喜欢
    • 2023-02-11
    • 2018-06-05
    • 1970-01-01
    • 2020-10-06
    • 2020-10-20
    • 2013-01-13
    • 1970-01-01
    • 2013-08-21
    • 2010-11-10
    相关资源
    最近更新 更多