我想在将消息发布到 rebus 时捕获有关当前用户的信息,以便处理程序和 saga 可以透明且正确地访问应用程序用户信息。我在源代码中有点迷失了,但基本上我正在尝试设置几件事:
消息发布时运行的钩子,并将当前用户信息放入标头
当收到消息并重写 ClaimsPrincipal.Current 时在 worker 中运行的钩子。
处理完成时在工作人员中运行并重置 ClaimsPrincipal.Current 的钩子。
任何建议,将不胜感激。
我想在将消息发布到 rebus 时捕获有关当前用户的信息,以便处理程序和 saga 可以透明且正确地访问应用程序用户信息。我在源代码中有点迷失了,但基本上我正在尝试设置几件事:
消息发布时运行的钩子,并将当前用户信息放入标头
当收到消息并重写 ClaimsPrincipal.Current 时在 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);
}
为了自动将当前经过身份验证的用户名传输到所有传出消息。
我建议您使用内置rebus-username
标头来传输用户名,因为 Rebus 可以使用它通过使用行为配置器在接收端建立当前主体,如关于用户上下文的 wiki 页面上所述