How to send messages to azure service bus queue using rest?
Published Feb 13 2020 01:58 AM 3,697 Views


Hello there, folks! I’d like to share a C# code snippet and PowerShell script which can be helpful in getting SAS token and use it in scenario sending message to service bus queue but with rest calls.


Below is the method by which we can generate SAS token:-

C# Sample for SAS token generate:


        static void Main(string[] args)


            string queueUrl = "https://<yournamespace>" + "<yourqueuename>";

            string token = GetSasToken(queueUrl, "<youraccesskeyname>", "<youraccesskeyvalue>", TimeSpan.FromDays(1));


        public static string GetSasToken(string resourceUri, string keyName, string key, TimeSpan ttl)


            var expiry = GetExpiry(ttl);

            string stringToSign = HttpUtility.UrlEncode(resourceUri) + "\n" + expiry;

            HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));

            var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));

            var sasToken = String.Format(CultureInfo.InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}",

            HttpUtility.UrlEncode(resourceUri), HttpUtility.UrlEncode(signature), expiry, keyName);

            return sasToken;



        private static string GetExpiry(TimeSpan ttl)


            TimeSpan expirySinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1) + ttl;

            return Convert.ToString((int)expirySinceEpoch.TotalSeconds);



PowerShell Script for SAS token generate:

[Reflection.Assembly]::LoadWithPartialName("System.Web")| out-null


$uri = 'https://<yournamespace><yourqueuename>'



#Token expires now+300


#Building Token

$SignatureString=[System.Web.HttpUtility]::UrlEncode($URI)+ "`n" + [string]$Expires

$HMAC = New-Object System.Security.Cryptography.HMACSHA256

$HMAC.key = [Text.Encoding]::ASCII.GetBytes($Access_Policy_Key)

$Signature = $HMAC.ComputeHash([Text.Encoding]::ASCII.GetBytes($SignatureString))

$Signature = [Convert]::ToBase64String($Signature)

$SASToken = "SharedAccessSignature sr=" + [System.Web.HttpUtility]::UrlEncode($URI) + "&sig=" + [System.Web.HttpUtility]::UrlEncode($Signature) + "&se=" + $Expires + "&skn=" + $Access_Policy_Name


$headerParams = @{'Authorization'="$($SASToken)"}



PS Output:

SAS Token output from PSScriptSAS Token output from PSScript


Finally, you can make a call to service bus queue to create message using any Http client.


POST call to create message in service bus queuePOST call to create message in service bus queue



Version history
Last update:
‎Feb 13 2020 01:58 AM
Updated by: