【问题标题】:When executing API method using MediatR, getting an error使用 MediatR 执行 API 方法时,出现错误
【发布时间】:2020-05-13 20:35:45
【问题描述】:

这是我第一次实现 Mediator,但现在调用 API 方法时出现以下错误:

错误

{"error":"Enumerator failed to MoveNextAsync."}

DI

services.AddMediatR(Assembly.GetExecutingAssembly());
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestValidationBehavior<,>));

基础 API

[ApiController]
[Route("api/[controller]")]
public abstract class ApiController : ControllerBase
{
    private IMediator _mediator;

    protected IMediator Mediator => _mediator ??= HttpContext.RequestServices.GetService<IMediator>();
}

API

[HttpGet]
[Route("client/{clientId}/template/list")]
public async Task<ActionResult<TemplateListDTO>> GetClientTemplateList(long clientId)
{
    return await Mediator.Send(new GetClientTemplateListQuery { ClientId = clientId });
}

我正在使用 DotNet 核心 3.1

【问题讨论】:

    标签: c# asp.net-core mediatr


    【解决方案1】:

    这里描述了这个问题:

    https://github.com/jbogard/MediatR/issues/317

    啊。你不能用 vanilla 做泛型类型约束 MS.Extensions.DI。请参阅我的 PR 以解决此问题: https://github.com/aspnet/DependencyInjection/pull/635

    执行以下操作:

    services.AddScoped(typeof(IPipelineBehavior<CustomerAddRequest, CommandResponse>), typeof(CustomerAddBehavior<CustomerAddRequest, CommandResponse>));
    services.AddScoped(typeof(IPipelineBehavior<BrandDeleteRequest, CommandResponse>), typeof(BrandDeleteBehavior<BrandDeleteRequest, CommandResponse>));
    services.AddScoped(typeof(IPipelineBehavior<CustomerDeleteRequest, CommandResponse>), typeof(CustomerDeleteBehavior<CustomerDeleteRequest, CommandResponse>));
    

    【讨论】:

      【解决方案2】:

      我发现了问题,不是 Mediator 的问题。管道发生异常,处理不正确,无法进入 next() 管道。

      【讨论】:

      • 我遇到了同样的问题。您是如何在启动时捕获异常的?谢谢。
      • @CidaoPapito,我的问题不是在启动时而是在管道过程中未处理的期望。我使用自定义类为其添加了一个附加层,因此我必须在那里捕获异常
      • 你有机会分享你的代码吗?我不确定如何使用自定义类添加此层以处理启动中的异常。我确实尝试在其他启动中添加一些 TRY CATCH 以捕获最终的异常,但它没有发生。任何帮助我将不胜感激。当它是 JWT 身份验证控制器时,只会发生我的错误“与”中介。这是情况的奇怪部分
      猜你喜欢
      • 2015-10-26
      • 1970-01-01
      • 2013-10-07
      • 2013-01-08
      • 1970-01-01
      • 2021-10-28
      • 2019-06-07
      • 2019-04-10
      • 1970-01-01
      相关资源
      最近更新 更多