skip to Main Content

Traditionally we when a message is sent to a queue it has a specific type so it can easily be deserialized into a specific type

However, I now have a situation where I need to send 2 totally different types of message on to the same queue

[FunctionName("MyFunction")]
public async Task QueueMessageReceivedAsync(
        [ServiceBusTrigger("%QueueName%", Connection = "event-bus-connection")]
        string mySbMsg)
{
    //If message.Label == "MessageType1"
    {
        var messageType1Object = JsonConvert.DeserializeObject<MessageType1>(mySbMsg);
                var okResponse = await ProcessMessageType1(messageType1Object);
        return okResponse;
    }
    else
    {
        var messageType2Object = JsonConvert.DeserializeObject<MessageType2>(mySbMsg);
        var okResponse = await ProcessMessageType(messageType2Object);
        return okResponse;
    }
}

This approach wont work because I dont know how to get to the underlying service bus message’s label property?

Its not an option for me to change the messages themselves in anyway. But the label of the underlying service bus message would allow me to process the message correctly

Can someone help please?

Paul

2

Answers


  1. It used to be possible to to define additional arguments to get system properties. string label to retrieve the label along with the message data. Also, irregardless of the .NET version, you can receive a Message (or BrokeredMessage if the Functions SDK is too old) and have access to the label property.

    Login or Signup to reply.
  2. It should work for you.

    [FunctionName("MyFunc")]
    public async Task Run(
        [ServiceBusTrigger(
            "%QueueName%",
            Connection = "ConnectionString")]
        string json,
        string label)
    {
         Console.WriteLine($"This is my body message {json}");
         Console.WriteLine($"This is my label/subject {label}");
    }
    

    The name of the variable label is by default assigned to the specific property of Message. The whole list of available props is there https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-service-bus-trigger?tabs=in-process%2Cfunctionsv2&pivots=programming-language-csharp#message-metadata.

    Gaurav Mantri‘s comment seems to indicate that it was impossible to use it in old ServiceBusTriggers before.

    You can use also other options like that:

    [FunctionName("MyFunc")]
    public async Task Run(
        [ServiceBusTrigger(
            "%QueueName%",
            Connection = "ConnectionString")]
        string json,
        Int32 deliveryCount,
        DateTime enqueuedTimeUtc,
        string messageId,
        string label)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search