c# - 自动向 Rebus 消息添加 header

标签 c# asp.net-web-api rebus

配置 Rebus 总线时,您可以指定它应该查找 Headers.UserName header ,如 here 所述。 .这允许您使用正确的用户名自动填充 Thread.CurrentPrincipal。这很好用,但我想知道是否有一种以标准方式设置 header 而不是在发送每条消息时手动设置 header 的好方法。

我正在构建一个基于 ASP.NET Web API 的服务,并希望每个请求都将 header 设置为在 apiControllerInstance.RequestContext.Principal.Identity.Name 中找到的名称。

一个不错的解决方案是在可以访问消息总线的基础 ApiController 上创建一个方法,因此您可以执行如下操作:

public IHttpActionResult SomeAction(SomeMessage message)
{
    SendWithUser(message);
    return Ok();
}

问题是你必须记住要这样做,所以我想得到一些关于如何以更一般的方式做到这一点的建议。此外,其他 header 将来可能会变得相关,这也会对这种方法产生问题。

更新

根据 mookid 的回答,我提出了以下解决方案(我刚刚验证它适用于我的一个请求,但我不保证稳健性):

public static void SetUserNameHeaderWhenCurrentPrincipalIsPresent(this IRebusEvents events)
{
    events.MessageSent += (bus, destination, message) =>
    {
        if (HttpContext.Current.User != null && !string.IsNullOrWhiteSpace(HttpContext.Current.User.Identity.Name))
            bus.AttachHeader(message, Headers.UserName, HttpContext.Current.User.Identity.Name);
    };
}

用法:

.Events(e => e.SetUserNameHeaderWhenCurrentPrincipalIsPresent())

最佳答案

你可以使用

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

为每条传出消息调用 SetUsername,您可以在此处查找 HttpContext.Current

请让我知道这对您来说效果如何,或者如果您认为还缺少其他东西:)

关于c# - 自动向 Rebus 消息添加 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20142118/

相关文章:

c# - ASP.net Web Api 版本控制

authentication - 不记名 token 如何在 Web API 2 中的服务器端存储?

javascript - 删除#!来自 ASP.Net Web API 中的 angular.js URL

unit-testing - Saga 处理程序在 rebus 和相关性问题中的单元测试

c# - 使用 C# 异步套接字读取面向行的数据

c# - ObservableCollection "cannot be used on the current platform"的 Json.NET 序列化

c# - 如何从其 Click 事件 WPF 中停止按钮命令的执行

c# - 使用 WCF 的分布式事务

c# - 将事件重新提交到 rebus