首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在ASP.NET Core-6 Web中,Fluent验证失败

在ASP.NET Core-6 Web中,Fluent验证失败
EN

Stack Overflow用户
提问于 2022-07-01 19:42:32
回答 2查看 825关注 0票数 2

在ASP.NET Core-6WebAPI中,我正在实现Fluent验证。

我有这样的模型:

模型:

代码语言:javascript
复制
public class Employee
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string RegistrationNumber { get; set; }
}

Dto:

代码语言:javascript
复制
public class EmployeeCreateDto
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string RegistrationNumber { get; set; }
}

之后,我使用fluent验证在这里进行了验证:

代码语言:javascript
复制
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的映射在这里完成:

代码语言:javascript
复制
public class MapperProfile: Profile
{
    public MapperProfile()
    {
        CreateMap<EmployeeCreateDto, Employee>().ReverseMap();
        CreateMap<Employee, AllEmployeeListDto>().ReverseMap();
        CreateMap<BankUserCreateDto, BankUser>().ReverseMap();
    }
}

EmployeeService:

代码语言:javascript
复制
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配置:

代码语言:javascript
复制
public static class AutoMapperServiceExtension
{
    public static void ConfigureAutoMappers(this IServiceCollection services)
    {
        services.AddAutoMapper(typeof(MapperProfile));
    }
}

还完成了依赖项注入。

代码语言:javascript
复制
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:

代码语言:javascript
复制
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.如果输入正确的数据,它将成功地将所有内容插入数据库。

但是,如果我故意输入不正确的数据,我希望它能在流畅验证的帮助下显示出来。但这不会发生的。数据只会被插入。

我该怎么解决这个问题?

谢谢

EN

回答 2

Stack Overflow用户

发布于 2022-07-04 11:11:10

您必须将验证逻辑放在同一个构造函数中。

尝尝这个。

代码语言:javascript
复制
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")
}
票数 0
EN

Stack Overflow用户

发布于 2022-08-23 04:38:34

移除这个

代码语言:javascript
复制
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;
                });

并在您的程序文件中添加以下内容

代码语言:javascript
复制
builder.Services.AddValidatorsFromAssemblyContaining<YourValidtor>();

然后在构造函数中注入IValidator验证器。那么在你的行动中

代码语言:javascript
复制
 ValidationResult result = await _validator.ValidateAsync(city);
            if (!result.IsValid)
            {
                result.AddToModelState(this.ModelState);
                
                return BadRequest(result);
            }

希望这能帮上忙

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72833977

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档