Search code examples
azureazureservicebusazure-servicebus-topics

Azure service bus - how to add metadata to the message


I am using .net core web app as the publisher and .net core console app as subscriber. I am able to successfully pass messages between these two systems using Managed Identities - set up in Azure portal.

My question is I need to add metadata to the the message that is being sent. How do I do that ?

Below is my publisher code :

string data = JsonConvert.SerializeObject(payloadEvents);
Message message = new Message(Encoding.UTF8.GetBytes(data));

var tokenProvider = TokenProvider.CreateManagedIdentityTokenProvider();

TopicClient sendClient = new TopicClient(_serviceBusNamespace, _topicName, tokenProvider, retryPolicy: null);

await sendClient.SendAsync(message);


Solution

  • Message object has a property called UserProperties that can be used to set custom metadata for that message.

    Something like:

    string data = JsonConvert.SerializeObject(payloadEvents);
    Message message = new Message(Encoding.UTF8.GetBytes(data));
    message.UserProperties.Add("key1", "value1");
    message.UserProperties.Add("key2", "value2");
    
    var tokenProvider = TokenProvider.CreateManagedIdentityTokenProvider();
    
    TopicClient sendClient = new TopicClient(_serviceBusNamespace, _topicName, tokenProvider, retryPolicy: null);
    
    await sendClient.SendAsync(message);