Appending username using headers

Component: NServiceBus
NuGet Package NServiceBus (5.x)

This sample demonstrates how to append the current username to outgoing messages and then how to extract that value when messages are handled.

Fake principal

For demonstration purposes, prior to sending a message, the Thread.CurrentPrincipal will be replaced with a new instance. In a production scenario, 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 for capturing the current user is to create a transport mutator that extracts the current identity and then adds it 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 :
    IMutateOutgoingTransportMessages
{
    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

busConfiguration.RegisterComponents(
    registration: components =>
    {
        components.ConfigureComponent<UsernameMutator>(DependencyLifecycle.InstancePerCall);
    });

The Handler

From within a handler (or saga) this value can be used as follows:

public class HandlerUsingCustomHeader :
    IHandleMessages<MyMessage>
{
    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