MassTransit RespondAsync 不能 Return 空值

MassTransit RespondAsync Cannot Return null Value

我正在使用 地铁

下面的代码 returns null 并且 Context.RespondAsync 不能 return null

当找不到城市时我想要 Return Null 并且在 Controller 中我检查响应是否为 null 然后 return Not Found

控制器:

 var request = _mediator.CreateRequestClient<TGetQuery>();

 GetCityQuery getQuery = _mapper.Map<GetCityQuery>(id);

 var result = await request.GetResponse<CityViewModel>(getQuery, cancellationToken);
 if (result.Message == null)
 {
      return NotFound();
 }
 return Ok(result.Message);

消费者:

public async Task Consume(ConsumeContext<GetCityQuery> context)
    {
        var cancellationToken = context.CancellationToken;
        var request = context.Message;
        var entity = await _cityRepository.TableNoTracking
            .ProjectTo<CityViewModel>(_mapper.ConfigurationProvider)
            .SingleOrDefaultAsync(x => x.Id == request.Id, cancellationToken);

        await context.RespondAsync(entity);
    }

所以 Masstransit Throw System.ArgumentNullException:值不能为空。 (参数 'message')在 MassTransit.Context.BaseConsumeContext.RespondAsync[T](T 消息)

有什么办法可以克服这个问题吗?

您不能使用 null 作为消息。如果你想为一个请求客户端使用多种响应类型,你可以分别指定类型:

var request = _mediator.CreateRequestClient<TGetQuery>();

 GetCityQuery getQuery = _mapper.Map<GetCityQuery>(id);

 var result = await request.GetResponse<CityViewModel, NotFound>(getQuery, cancellationToken);
 if (result.Is(out Response<CityViewModel> response)
 {
     return Ok(response.Message);
 }

return NotFound();

您需要定义消息类型:

public class NotFound
{
}

然后,在您的消费者中:

public async Task Consume(ConsumeContext<GetCityQuery> context)
{
     var request = context.Message;
     var entity = await _cityRepository.TableNoTracking
          .ProjectTo<CityViewModel>(_mapper.ConfigurationProvider)
          .SingleOrDefaultAsync(x => x.Id == request.Id, context.CancellationToken);
     if(entity == null)
          await context.RespondAsync(new NotFound());
     else
          await context.RespondAsync(entity);
}