如何在 UWP 应用程序中使用 Azure 通知中心标签推送消息

How to use azure notification hub tags for push messages in UWP apps

我想将推送消息发送到特定渠道中的应用程序,例如“en-us”和“fr-fr”以本地化推送通知。

首先我按照本教程进行操作,一切正常: https://docs.microsoft.com/en-us/azure/notification-hubs/notification-hubs-windows-store-dotnet-get-started-wns-push-notification

那里的工作注册是:

var result = await hub.RegisterNativeAsync(channel.Uri);

但这就是向所有客户端发送一条消息。然后我跟着这个教程: https://docs.microsoft.com/en-us/azure/notification-hubs/notification-hubs-windows-notification-dotnet-push-xplat-segmented-wns

我可以从与 uwp 代码的混乱混合中提取的是这一行:

var hub = new NotificationHub("AppName", "endpoint");
            
            const string templateBodyWNS = "<toast><visual><binding template=\"ToastText01\"><text id=\"1\">$(messageParam)</text></binding></visual></toast>";

            var result = await hub.RegisterTemplateAsync(channel.Uri, templateBodyWNS, "simpleWNSTemplateExample", new string[] { "en-us" });

结果也给了我一个有效的注册。

然后我尝试使用 azure notfication hub 控制台对其进行测试(该控制台与上一步一起将其发送给所有客户端:

这导致应用收到通知(它不会过滤“en-us”)。 然后我试着把“en-us”放在“发送到标签表达式”中:

至此,没有 toast 消息到达。

然后我尝试通过 Microsoft.Azure.NotificationHubs 包裹发送消息。

此代码有效:

NotificationHubClient Hub = NotificationHubClient.CreateClientFromConnectionString(endpoint,  name);
            string toast = @"<?xml version='1.0' encoding='utf-8'?>
  <toast>
  <visual><binding template='ToastText01'>
     <text id='1'> Test message </text>
          </binding>
          </visual>
          </toast>
          ";
      var result = await     Hub.SendWindowsNativeNotificationAsync(toast);
   

Toast 消息到达。但是一旦我将最后一行更改为:

var result = await Hub.SendWindowsNativeNotificationAsync(toast, "en-us");

没有到达。 所以Notification Hub通过WNS成功链接到客户端,但是使用tags根本不起作用。我做错了什么?

好的,我想通了,这里有任何有同样问题的人:

首先,由于其他人也可能对此感到困惑,因此我们需要了解定义推送模板的概念与 FCM(对于 Android)的工作方式不同。在 FCM 中,您定义推送消息服务器端的布局和内容。

在 UWP 中,它发生在客户端使用标签时。在设计 toast 时,您可以将变量放入其中,然后由服务器端填充。

这是工作代码。

客户端:

var hub = new NotificationHub("Hubname", "endpoint");
string toast = @"<toast>
<visual><binding template='ToastGeneric'>
<text id='1'>$(Title)</text>
<text id='2'>$(Message)</text>

<text placement='attribution'>via SMS</text>
</binding>
</visual>
</toast>
";
var result = await hub.RegisterTemplateAsync(channel.Uri, toast, localizedWNSTemplateExample", new string[] { "myTag" });

服务器端:

NotificationHubClient Hub = NotificationHubClient.CreateClientFromConnectionString(endpoint, name);
Dictionary<string, string> templateParams = new Dictionary<string, string>();
templateParams["Title"] = "Title here";
templateParams["Message"] = "Message here";
await Hub.SendTemplateNotificationAsync(templateParams, "myTag");

您还可以使用“自定义模板”平台从 Web 发送消息:

不确定“自定义模板”是否也可以与 android 和 iOS 一起使用。太棒了。