Azure Service Bus trigger for Azure Functions

Use the Service Bus trigger to respond to messages from a Service Bus queue or topic. Starting with extension version 3.1.0, you can trigger on a session-enabled queue or topic.

For information on setup and configuration details, see the overview.

Example

The following example shows a C# function that reads message metadata and logs a Service Bus queue message:

[FunctionName("ServiceBusQueueTriggerCSharp")]                    
public static void Run(
    [ServiceBusTrigger("myqueue", Connection = "ServiceBusConnection")] 
    string myQueueItem,
    Int32 deliveryCount,
    DateTime enqueuedTimeUtc,
    string messageId,
    ILogger log)
{
    log.LogInformation($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
    log.LogInformation($"EnqueuedTimeUtc={enqueuedTimeUtc}");
    log.LogInformation($"DeliveryCount={deliveryCount}");
    log.LogInformation($"MessageId={messageId}");
}

Attributes and annotations

In C# class libraries, use the following attributes to configure a Service Bus trigger:

  • ServiceBusTriggerAttribute

    The attribute's constructor takes the name of the queue or the topic and subscription. In Azure Functions version 1.x, you can also specify the connection's access rights. If you don't specify access rights, the default is Manage. For more information, see the Trigger - configuration section.

    Here's an example that shows the attribute used with a string parameter:

    [FunctionName("ServiceBusQueueTriggerCSharp")]                    
    public static void Run(
        [ServiceBusTrigger("myqueue")] string myQueueItem, ILogger log)
    {
        ...
    }
    

    Since the Connection property isn't defined, Functions looks for an app setting named AzureWebJobsServiceBus, which is the default name for the Service Bus connection string. You can also set the Connection property to specify the name of an application setting that contains the Service Bus connection string to use, as shown in the following example:

    [FunctionName("ServiceBusQueueTriggerCSharp")]                    
    public static void Run(
        [ServiceBusTrigger("myqueue", Connection = "ServiceBusConnection")] 
        string myQueueItem, ILogger log)
    {
        ...
    }
    

    For a complete example, see Trigger - example.

  • ServiceBusAccountAttribute

    Provides another way to specify the Service Bus account to use. The constructor takes the name of an app setting that contains a Service Bus connection string. The attribute can be applied at the parameter, method, or class level. The following example shows class level and method level:

    [ServiceBusAccount("ClassLevelServiceBusAppSetting")]
    public static class AzureFunctions
    {
        [ServiceBusAccount("MethodLevelServiceBusAppSetting")]
        [FunctionName("ServiceBusQueueTriggerCSharp")]
        public static void Run(
            [ServiceBusTrigger("myqueue", AccessRights.Manage)] 
            string myQueueItem, ILogger log)
    {
        ...
    }
    

The Service Bus account to use is determined in the following order:

  • The ServiceBusTrigger attribute's Connection property.
  • The ServiceBusAccount attribute applied to the same parameter as the ServiceBusTrigger attribute.
  • The ServiceBusAccount attribute applied to the function.
  • The ServiceBusAccount attribute applied to the class.
  • The "AzureWebJobsServiceBus" app setting.

Configuration

The following table explains the binding configuration properties that you set in the function.json file and the ServiceBusTrigger attribute.

function.json property Attribute property Description
type n/a Must be set to "serviceBusTrigger". This property is set automatically when you create the trigger in the Azure portal.
direction n/a Must be set to "in". This property is set automatically when you create the trigger in the Azure portal.
name n/a The name of the variable that represents the queue or topic message in function code.
queueName QueueName Name of the queue to monitor. Set only if monitoring a queue, not for a topic.
topicName TopicName Name of the topic to monitor. Set only if monitoring a topic, not for a queue.
subscriptionName SubscriptionName Name of the subscription to monitor. Set only if monitoring a topic, not for a queue.
connection Connection The name of an app setting that contains the Service Bus connection string to use for this binding. If the app setting name begins with "AzureWebJobs", you can specify only the remainder of the name. For example, if you set connection to "MyServiceBus", the Functions runtime looks for an app setting that is named "AzureWebJobsMyServiceBus". If you leave connection empty, the Functions runtime uses the default Service Bus connection string in the app setting that is named "AzureWebJobsServiceBus".

To obtain a connection string, follow the steps shown at Get the management credentials. The connection string must be for a Service Bus namespace, not limited to a specific queue or topic.
accessRights Access Access rights for the connection string. Available values are manage and listen. The default is manage, which indicates that the connection has the Manage permission. If you use a connection string that does not have the Manage permission, set accessRights to "listen". Otherwise, the Functions runtime might fail trying to do operations that require manage rights. In Azure Functions version 2.x and higher, this property is not available because the latest version of the Service Bus SDK doesn't support manage operations.
isSessionsEnabled IsSessionsEnabled true if connecting to a session-aware queue or subscription. false otherwise, which is the default value.

When you're developing locally, app settings go into the local.settings.json file.

Usage

The following parameter types are available for the queue or topic message:

  • string - If the message is text.
  • byte[] - Useful for binary data.
  • A custom type - If the message contains JSON, Azure Functions tries to deserialize the JSON data.
  • BrokeredMessage - Gives you the deserialized message with the BrokeredMessage.GetBody<T>() method.
  • MessageReceiver - Used to receive and acknowledge messages from the message container (required when autoComplete is set to false)

These parameter types are for Azure Functions version 1.x; for 2.x and higher, use Message instead of BrokeredMessage.

Poison messages

Poison message handling can't be controlled or configured in Azure Functions. Service Bus handles poison messages itself.

PeekLock behavior

The Functions runtime receives a message in PeekLock mode. It calls Complete on the message if the function finishes successfully, or calls Abandon if the function fails. If the function runs longer than the PeekLock timeout, the lock is automatically renewed as long as the function is running.

The maxAutoRenewDuration is configurable in host.json, which maps to OnMessageOptions.MaxAutoRenewDuration. The maximum allowed for this setting is 5 minutes according to the Service Bus documentation, whereas you can increase the Functions time limit from the default of 5 minutes to 10 minutes. For Service Bus functions you wouldn’t want to do that then, because you’d exceed the Service Bus renewal limit.

Message metadata

The Service Bus trigger provides several metadata properties. These properties can be used as part of binding expressions in other bindings or as parameters in your code. These properties are members of the Message class.

Property Type Description
ContentType string A content type identifier utilized by the sender and receiver for application-specific logic.
CorrelationId string The correlation ID.
DeadLetterSource string The dead letter source.
DeliveryCount Int32 The number of deliveries.
EnqueuedTimeUtc DateTime The enqueued time in UTC.
ExpiresAtUtc DateTime The expiration time in UTC.
Label string The application-specific label.
MessageId string A user-defined value that Service Bus can use to identify duplicate messages, if enabled.
MessageReceiver MessageReceiver Service Bus message receiver. Can be used to abandon, complete, or deadletter the message.
MessageSession MessageSession A message receiver specifically for session-enabled queues and topics.
ReplyTo string The reply to queue address.
SequenceNumber long The unique number assigned to a message by the Service Bus.
To string The send to address.
UserProperties IDictionary<string, object> Properties set by the sender.

See code examples that use these properties earlier in this article.

Next steps