Getting Started
Architecture
NServiceBus
Transports
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring
Modernization
Samples

Aborting Pipeline execution

Component: NServiceBus
NuGet Package: NServiceBus 9.x

NServiceBus allows for aborting handlers execution. This can be done either from within a message handler or by using a custom pipeline behavior.

From inside a Handler

If the endppoint hosts more than one handler for the same message type, from the context of an handler, further handler execution can be aborted by calling the DoNotContinueDispatchingCurrentMessageToHandlers() method. This method instructs the NServiceBus not to pass the current message on to subsequent handlers in the pipeline. This is often used by authentication and authorization handlers when those checks fail.

class Handler :
    IHandleMessages<MyMessage>
{
    public Task Handle(MyMessage message, IMessageHandlerContext context)
    {
        context.DoNotContinueDispatchingCurrentMessageToHandlers();
        return Task.CompletedTask;
    }
}

Via a pipeline Behavior

The pipeline can also be aborted by injecting a custom Behavior that, with some custom logic, optionally decides to abort any nested behaviors.

public class Behavior :
    Behavior<IIncomingLogicalMessageContext>
{
    public override Task Invoke(IIncomingLogicalMessageContext context, Func<Task> next)
    {
        if (ShouldPipelineContinue(context))
        {
            return next();
        }
        // since next is not invoke all downstream behaviors will be skipped
        return Task.CompletedTask;
    }

    bool ShouldPipelineContinue(IIncomingLogicalMessageContext context)
    {
        // the custom logic to determine if the pipeline should continue
        return true;
    }
}

For more information about creating and injecting a behavior, see customizing the pipeline.