Masstransit .NET:是否有可能在消费过滤器中获得响应?



目前我们在masstrtransit中介中使用了一组消费过滤器,即用于验证、事务等。在API控制器和消费者之间,我们将使用Request/Response

startup.cs中的示例:

services.AddMediator(x =>
{
x.ConfigureMediator((context, cfg) =>
{
cfg.UseConsumeFilter(typeof(LoggingConsumeFilter<>), context);
cfg.UseConsumeFilter(typeof(ValidationFilter<>),context);
cfg.UseConsumeFilter(typeof(ContextUserFilter<>),context);
cfg.UseConsumeFilter(typeof(TransactionConsumeFilter<>),context);
});
x.AddConsumersFromNamespaceContaining<GetDynFieldSectionModelQueryConsumer>();

现在我计划添加一个新的过滤器" anonymisationconsumerfilter ",其思想是过滤器将在消费者完成后更改响应。在我们的例子中,响应在某些情况下应该是匿名的(例如,如果用户没有访问VIP用户的权限)。

第一个想法是像这样添加一个过滤器:
public class AnonymisationConsumeFilter<TMessage> : IFilter<ConsumeContext<TMessage>>
where TMessage : class
{
private readonly ILogger<TMessage> logger;
private readonly IHttpContextAccessor httpContextAccessor;
private readonly RoleAccessLevelOptions roleAccessLevelOptions;
public AnonymisationConsumeFilter(ILogger<TMessage> logger, IHttpContextAccessor httpContextAccessor, IOptions<RoleAccessLevelOptions> roleAccessLevelOptions)
{
this.logger = logger;
this.httpContextAccessor = httpContextAccessor;
this.roleAccessLevelOptions = roleAccessLevelOptions.Value;
}
public void Probe(ProbeContext context)
{
context.CreateFilterScope("make-anonymisation");
}
public async Task Send(ConsumeContext<TMessage> context, IPipe<ConsumeContext<TMessage>> next)
{
var requestName = typeof(TMessage).Name;
await next.Send(context);
if (context.<how to get the response???> is not IResponseAccessLevel objectWithAccessLevel)
{
logger.LogWarning($"----- Make anonymisation for non IResponseAccessLevel objects is ignored, Request {requestName} {context.Message}");
}
else
{
var response = context.<how to get the response???>
[...]
AnonymisationHelper.MakeAnonymous(response);
}
}
}

目前,我不认为有可能使用消费过滤器从消费者那里获得响应。目前我看到的唯一可能是使用消息有效负载。但是如何修改过滤器中的响应并返回给调用者呢?

提前谢谢你…

响应实际上是发送回请求发起者,因此为了拦截响应,您需要添加一个发送过滤器。作用域的发送过滤器类似于消费过滤器,但是是围绕SendContext<T>构建的。范围将在消费过滤器和发送过滤器之间共享。

此外,您可以在将其发送给消费者之前向消费过滤器中的有效负载添加一些内容,然后在发送过滤器中检查有效负载中是否有ConsumeContext,然后从ConsumeContext请求自定义有效负载并在发送过滤器中使用它。

最新更新