在ASP.NET Core-6WebAPI中,我正在实现Fluent验证。
我有这样的模型:
模型:
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string RegistrationNumber { get; set; }
}Dto:
public class EmployeeCreateDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string RegistrationNumber { get; set; }
}之后,我使用fluent验证在这里进行了验证:
public class EmployeeCreateDtoValidator : AbstractValidator<EmployeeCreateDto>
{
private readonly ApplicationDbContext _dbContext;
public EmployeeCreateDtoValidator(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public EmployeeCreateDtoValidator()
{
RuleFor(user => user.FirstName)
.NotEmpty().WithMessage("First Name field is required. ERROR!")
.NotNull().WithMessage("First Name cannot be null");
RuleFor(user => user.LastName)
.NotEmpty().WithMessageLast Name cannot be null");
RuleFor(user => user.RegistrationNumber)
.Must(BeUniqueRegistrationNumber).WithMessage("The specified Registration Number already exists.")
.NotEmpty().WithMessage("Registration Number field is required. ERROR!")
.NotNull().WithMessage("Registration Number cannot be null")
}
private bool BeUniqueRegistrationtNumber(string name)
{
if (_dbContext.Employees.SingleOrDefault(x => x.RegistrationNumber.ToLower() == name.ToLower()) == null) return true;
return false;
}
}到Dto的映射在这里完成:
public class MapperProfile: Profile
{
public MapperProfile()
{
CreateMap<EmployeeCreateDto, Employee>().ReverseMap();
CreateMap<Employee, AllEmployeeListDto>().ReverseMap();
CreateMap<BankUserCreateDto, BankUser>().ReverseMap();
}
}EmployeeService:
public async Task<Response<AllEmployeeListDto>> CreateEmployeeAsyncEmployeeCreateDto model)
{
var existingEmployee = await _dbContext.Employees.FirstOrDefaultAsync(e => e.RegistrationNumber == model.RegistrationNumber);
var response = new Response<AllEmployeeListDto>();
using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
if (existingEmployee == null)
{
if (result.Succeeded)
{
var employee = _mapper.Map<Employee>(model);
await _unitOfWork.Employees.InsertAsync(employee);
await _unitOfWork.Save();
response.StatusCode = (int)HttpStatusCode.Created;
response.Successful = true;
response.Data = _mapper.Map<AllEmployeeListDto>(employee);
response.Message = "Employee Created Successfully!";
transaction.Complete();
return response;
}
}
else
{
transaction.Dispose();
response.StatusCode = (int)HttpStatusCode.BadRequest;
response.Successful = false;
response.Message = "Registration failed. Please try again";
return response;
}
return response;
};
}AutoMapper配置:
public static class AutoMapperServiceExtension
{
public static void ConfigureAutoMappers(this IServiceCollection services)
{
services.AddAutoMapper(typeof(MapperProfile));
}
}还完成了依赖项注入。
public static class DIServiceExtension
{
public static void AddDependencyInjection(this IServiceCollection services)
{
// Add Service Injections Here -- Employee
services.AddScoped<IEmployeeService, EmployeeService>();
//services.AddScoped<IHttpClientService, HttpClientService>();
// Add Repository Injections Here
services.AddScoped<IUnitOfWork, UnitOfWork>();
// Add Fluent Validator Injections Here
// Employee Validator
services.AddTransient<IValidator<EmployeeCreateDto>, EmployeeCreateDtoValidator>();
}
}最后,我有了Program.cs
Program.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();
string? port = Environment.GetEnvironmentVariable("PORT");
if (!string.IsNullOrWhiteSpace(port))
{
app.Urls.Add("http://*:" + port);
}
app.Run();我想我在流畅的验证配置上有问题。我正在使用ASP.NET核心-6.如果输入正确的数据,它将成功地将所有内容插入数据库。
但是,如果我故意输入不正确的数据,我希望它能在流畅验证的帮助下显示出来。但这不会发生的。数据只会被插入。
我该怎么解决这个问题?
谢谢
发布于 2022-07-04 11:11:10
您必须将验证逻辑放在同一个构造函数中。
尝尝这个。
public EmployeeCreateDtoValidator(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
RuleFor(user => user.FirstName)
.NotEmpty().WithMessage("First Name field is required. ERROR!")
.NotNull().WithMessage("First Name cannot be null");
RuleFor(user => user.LastName)
.NotEmpty().WithMessageLast Name cannot be null");
RuleFor(user => user.RegistrationNumber)
.Must(BeUniqueRegistrationNumber).WithMessage("The specified Registration Number already exists.")
.NotEmpty().WithMessage("Registration Number field is required. ERROR!")
.NotNull().WithMessage("Registration Number cannot be null")
}发布于 2022-08-23 04:38:34
移除这个
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;
});
并在您的程序文件中添加以下内容
builder.Services.AddValidatorsFromAssemblyContaining<YourValidtor>();
然后在构造函数中注入IValidator验证器。那么在你的行动中
ValidationResult result = await _validator.ValidateAsync(city);
if (!result.IsValid)
{
result.AddToModelState(this.ModelState);
return BadRequest(result);
}
希望这能帮上忙
https://stackoverflow.com/questions/72833977
复制相似问题