Appending username using headers

Component: NServiceBus
NuGet Package NServiceBus (6.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();
await endpointInstance.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 Task MutateOutgoing(MutateOutgoingTransportMessageContext context)
        log.Info("Adding Thread.CurrentPrincipal user to headers");
        context.OutgoingHeaders["UserName"] = Thread.CurrentPrincipal.Identity.Name;
        return Task.CompletedTask;

Register the Mutator

endpointConfiguration.RegisterMessageMutator(new UsernameMutator());

The Handler

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

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

    public Task Handle(MyMessage message, IMessageHandlerContext context)
        var headers = context.MessageHeaders;
        var usernameFromHeader = headers["UserName"];
        log.Info($"Username extracted from header: {usernameFromHeader}");
        return Task.CompletedTask;

Related Articles

Last modified