【发布时间】: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