Appending username using headers

Component: NServiceBus
NuGet Package NServiceBus (5.x)

This sample shows appending the current username to outgoing messages and then extracting that value during message handling.

Fake Principal

For demonstration purposes, prior to sending a message, the Thread.CurrentPrincipal will be replaced with a new instance. Normally in production the Thread.CurrentPrincipal would be either the impersonated user from IIS or the current user sending a message.

var identity = new GenericIdentity("FakeUser");
Thread.CurrentPrincipal = new GenericPrincipal(identity, new string[0]);
var message = new MyMessage();
bus.Send("Samples.UsernameHeader.Endpoint2", message);

Custom Header with a Mutator

The recommended approach to capturing the current user is to create a transport mutator that extracts the current identity and adds that to the header of every outgoing message.

Outgoing Mutator

The outgoing mutator extracts Thread.CurrentPrincipal.Identity.Name and appends it to a message header.

public class UsernameMutator :
    static ILog log = LogManager.GetLogger("Handler");

    public void MutateOutgoing(LogicalMessage logicalMessage, TransportMessage transportMessage)
        log.Info("Adding Thread.CurrentPrincipal user to headers");
        transportMessage.Headers["UserName"] = Thread.CurrentPrincipal.Identity.Name;

Register the Mutator

    registration: components =>

The Handler

From within a Handler (or Saga) this value can be used as such.

public class HandlerUsingCustomHeader :
    static ILog log = LogManager.GetLogger("HandlerUsingCustomHeader");
    IBus bus;

    public HandlerUsingCustomHeader(IBus bus)
        this.bus = bus;

    public void Handle(MyMessage message)
        var headers = bus.CurrentMessageContext.Headers;
        var usernameFromHeader = headers["UserName"];
        log.Info($"Username extracted from header: {usernameFromHeader}");

Related Articles

Last modified