使用RESTAPI向Azure服务总线队列或主题发送消息

使用RESTAPI向Azure服务总线队列或主题发送消息,azure,windows-phone-8,hmac,azureservicebus,azure-servicebus-queues,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。此类显示在前面的类型中,但在编译时它不存在 如何使用发送REST API将消息发送到服务总线

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

然后,我尝试使用Azure Service Bus REST API进行发送,但这需要我构建一个SAS令牌。但要构建SAS令牌,我需要使用Windows.Security.Cryptography.Core.MacAlgorithmNames.HmacSha256。此类显示在前面的类型中,但在编译时它不存在


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

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

您需要使用您唯一的服务总线名称空间和密钥更新示例,并且您可能希望将其存储在比方法中更好的位置

和中介绍了如何创建SAS令牌

我从

private static void SendSBMessage(字符串消息)
{
尝试
{
字符串baseUri=”https://.servicebus.windows.net";
使用(System.Net.Http.HttpClient client=new System.Net.Http.HttpClient())
{
client.BaseAddress=新Uri(baseUri);
client.DefaultRequestHeaders.Accept.Clear();
字符串标记=SASTokenHelper();
client.DefaultRequestHeaders.Authorization=新的AuthenticationHeaderValue(“SharedAccessSignature”,令牌);
字符串json=JsonConvert.SerializeObject(消息);
HttpContent=newstringcontent(json,Encoding.UTF8);
content.Headers.ContentType=新的MediaTypeHeaderValue(“应用程序/json”);
字符串路径=“//消息”;
var response=client.PostAsync(路径、内容).Result;
if(响应。IsSuccessStatusCode)
{
//做点什么
}
其他的
{
//做点别的
}
}
}
捕获(例外情况除外)
{
//处理问题
}
}
私有静态字符串SASTokenHelper()
{
string keyName=“RootManageSharedAccessKey”;
字符串键=”;
字符串uri=“.servicebus.windows.net”;
int expiry=(int)DateTime.UtcNow.AddMinutes(20).Subtract(newdatetime(1970,1,1)).TotalSeconds;
字符串stringToSign=WebUtility.UrlEncode(uri)+“\n”+expiry.ToString();
字符串签名=HmacSha256(键,stringToSign);
string-token=string.Format(“sr={0}&sig={1}&se={2}&skn={3}”,WebUtility.UrlEncode(uri),WebUtility.UrlEncode(signature),expiry,keyName);
返回令牌;
}
//因为Windows.Security.Cryptography.Core.MacAlgorithmNames.HmacSha256没有
//存在于WP8.1环境中,我们需要执行另一个实现
公共静态字符串HmacSha256(字符串键、字符串值)
{
var keyStrm=cryptographicsbuffer.ConvertStringToBinary(key,BinaryStringEncoding.Utf8);
var valueStrm=cryptographicsbuffer.ConvertStringToBinary(值,BinaryStringEncoding.Utf8);
var objMacProv=MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);
var hash=objMacProv.CreateHash(keyStrm);
hash.Append(valueStrm);
返回CryptographicBuffer.EncodeToBase64String(hash.GetValueAndReset());
}
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());
}