使用REST API向Azure Service Bus Queue或Topic发送消息

时间:2014-12-12 07:49:11

标签: azure windows-phone-8 hmac azureservicebus azure-servicebus-queues

我正在构建一个Windows Phone应用程序,但无法使用Microsoft.ServiceBus.Messaging.QueueClient类。

然后我尝试使用Azure Service Bus REST API执行发送,但这需要我构建SAS令牌。但是要构建SAS令牌,我需要使用Windows.Security.Cryptography.Core.MacAlgorithmNames.HmacSha256。此类以预先输入显示,但在编译时不存在。

如何使用Send REST API将消息发布到服务总线队列或主题?

1 个答案:

答案 0 :(得分:2)

我将包含使用REST API向服务总线发送消息的完整代码,包括创建SAS令牌和HmacSha256哈希。

您需要使用唯一的Service Bus命名空间和密钥更新示例,并且您可能希望将其存储在比方法更好的位置......

http://msdn.microsoft.com/library/azure/dn170477.aspxhttps://code.msdn.microsoft.com/windowsazure/Service-Bus-HTTP-Token-38f2cfc5中记录了如何创建SAS令牌。

我从HMACSHA256 on Windows Phone 8.1?

开始实施HmacSha256
private static void SendSBMessage(string message)
{
    try
    {
        string baseUri = "https://<your-namespace>.servicebus.windows.net";
        using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
        {
            client.BaseAddress = new Uri(baseUri);
            client.DefaultRequestHeaders.Accept.Clear();

            string token = SASTokenHelper();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("SharedAccessSignature", token);

            string json = JsonConvert.SerializeObject(message);
            HttpContent content = new StringContent(json, Encoding.UTF8);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            string path = "/<queue-or-topic-name>/messages"; 

            var response = client.PostAsync(path, content).Result;
            if (response.IsSuccessStatusCode)
            {
                // Do something
            }
            else
            {
                // Do something else
            }
        }
    }
    catch(Exception ex)
    {
        // Handle issue
    }
}

private static string SASTokenHelper()
{
    string keyName = "RootManageSharedAccessKey";
    string key = "<your-secret-key>";
    string uri = "<your-namespace>.servicebus.windows.net";

    int expiry = (int)DateTime.UtcNow.AddMinutes(20).Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
    string stringToSign = WebUtility.UrlEncode(uri) + "\n" + expiry.ToString();
    string signature = HmacSha256(key, stringToSign);
    string token = String.Format("sr={0}&sig={1}&se={2}&skn={3}", WebUtility.UrlEncode(uri), WebUtility.UrlEncode(signature), expiry, keyName);

    return token;
}

// Because Windows.Security.Cryptography.Core.MacAlgorithmNames.HmacSha256 doesn't
// exist in WP8.1 context we need to do another implementation
public static string HmacSha256(string key, string value)
{
    var keyStrm = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8);
    var valueStrm = CryptographicBuffer.ConvertStringToBinary(value, BinaryStringEncoding.Utf8);

    var objMacProv = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);
    var hash = objMacProv.CreateHash(keyStrm);
    hash.Append(valueStrm);

    return CryptographicBuffer.EncodeToBase64String(hash.GetValueAndReset());
}