使用 rebus 发布时如何捕获上下文信息

How can I capture context information when publishing with rebus

我想在向 rebus 发布消息时捕获有关当前用户的信息,以便处理程序和 sagas 能够透明和正确地访问应用程序用户信息。我有点迷失在源代码中,但基本上我正在尝试设置几件事:

  1. 发布消息时运行的钩子,将当前用户信息放入消息头

  2. 收到消息时在 worker 中运行并重写 ClaimsPrincipal.Current.

  3. 的挂钩
  4. 处理完成后在 worker 中运行并重置的挂钩 ClaimsPrincipal.Current。

如有任何建议,我们将不胜感激。

您可以使用 Rebus 的事件配置器连接 MessageSent 事件,只要发送外发消息(即发送以及发布和回复)就会触发该事件,如下所示:

 Configure.With(...)
     .(...)
     .Events(e => e.MessageSent += AutomaticallySetUsernameIfPossible)
     .(...)

然后你的 AutomaticallySetUsernameIfPossible 可能会做这样的事情:

void AutomaticallySetUsernameIfPossible(IBus bus, string destination, object message)
{
    var principal = Thread.CurrentPrincipal;
    if (principal == null) return;

    var identity = principal.Identity;
    if (identity == null) return;

    var name = identity.Name;
    if (string.IsNullOrWhitespace(name)) return;

    bus.AttachHeader(message, Headers.UserName, name);    
}

为了自动将当前经过身份验证的用户名传送到所有外发邮件。[​​=16=]

我建议你使用内置的 rebus-username header to transfer the username because it can be used by Rebus to establish the current principal on the receiving end by using the behavior configurer as decribed on the wiki page about user context