FluentValidation使用方法
安装包FluentValidation与FluentValidation.AspNetCore
新建GreetingCommand.cs文件
using FluentValidation;
using MediatR;
namespace WebApplication1
{
public class GreetingCommand : IRequest<string>
{
public string Name { get; set; }
public string? Age { get; set; }
}
public class GreetingCommandHandler : IRequestHandler<GreetingCommand, string>
{
public Task<string> Handle(GreetingCommand request, CancellationToken cancellationToken)
{
return Task.FromResult($"Hello, {request.Name}!");
}
}
public class GreetingCommandValidator : AbstractValidator<GreetingCommand>
{
public GreetingCommandValidator()
{
RuleFor(v => v.Age).NotEmpty().WithMessage("年龄不能为空");
}
}
public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>
{
private readonly IEnumerable<IValidator<TRequest>> _validators;
public ValidationBehavior(IEnumerable<IValidator<TRequest>> validators)
{
_validators = validators;
}
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
{
var context = new ValidationContext<TRequest>(request);
var failures = _validators
.Select(v => v.Validate(context))
.SelectMany(result => result.Errors)
.Where(f => f != null)
.ToList();
if (failures.Count != 0)
{
throw new ValidationException(failures);
}
return await next();
}
}
}
修改Program.cs文件
using WebApplication1;
using FluentValidation;
using FluentValidation.AspNetCore;
using MediatR;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddValidatorsFromAssemblyContaining<GreetingCommandValidator>();//注册FluentValidation
builder.Services.AddFluentValidationAutoValidation(); //让FluentValidation验证webapi的输入参数
// MediatR 注入FluentValidation验证
//builder.Services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
//builder.Services.AddSwaggerGen();
// Fix: Use the correct overload for AddMediatR
builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(GreetingCommandHandler).Assembly));
var app = builder.Build();
// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
//app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/openapi/v1.json", "v1");
});
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();