You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 6配置MediatR后验证器未触发问题及解决方法

MediatR验证管道未执行的问题及解决办法

我在测试项目中搭建CURD功能,使用了最新版本的MediatR NuGet包,配置代码如下:

services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly());

services.AddMediatR(cfg =>
{
    cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly());
    cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(ValidationBehaviour<,>), ServiceLifetime.Transient);
    cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(LoggingBehaviour<,>), ServiceLifetime.Scoped);
}); 

调用Mediator命令时,日志管道可以正常工作,但验证管道始终未执行。该配置代码写在.NET API项目的Program.cs中,项目引用了存放所有Command、Queries、ValidationBehaviour和LoggingBehaviour的Service项目,我查了不少线上资料都没能解决问题,想问问有没有类似配置且验证器能正常工作的案例?

问题解决

后来找到原因了:需要添加两种不同的验证管道实现,分别对应两种IRequest接口的泛型形式:

ValidationBehaviour1<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest

ValidationBehaviour2<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse>

内容的提问来源于stack exchange,提问作者LittleFunny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 11:22:36