使用 Azure 通知中心发送跨平台通知Send cross-platform notifications with Azure Notification Hubs

本教程基于前一教程:使用 Azure 通知中心向特定用户发送通知This tutorial builds on the previous tutorial, Send notifications to specific users by using Azure Notification Hubs. 该教程介绍了如何向注册给经过身份验证的特定用户的所有设备推送通知。That tutorial describes how to push notifications to all devices that are registered to a specific authenticated user. 该方法需要使用多个请求将通知发送到每个受支持的客户端平台。That approach required multiple requests to send a notification to each supported client platform. Azure 通知中心支持模板,可以通过模板指定特定设备要如何接收通知。Azure Notification Hubs supports templates, with which you can specify how a specific device wants to receive notifications. 此方法简化了发送跨平台通知的方式。This method simplifies sending cross-platform notifications.

本文演示了如何利用模板发送针对所有平台的通知。This article demonstrates how to take advantage of templates to send a notification that targets all platforms. 本文使用单个请求发送不区分平台的通知。This article uses a single request to send a platform neutral notification. 有关模板的更多详细信息,请参阅通知中心概述For more detailed information about templates, see Notification Hubs Overview.

重要

Visual Studio 2019 不支持使用 Windows Phone 项目 8.1 及更早的版本。Windows Phone projects 8.1 and earlier are not supported in Visual Studio 2019. 有关详细信息,请参阅 Visual Studio 2019 平台目标以及兼容性For more information, see Visual Studio 2019 Platform Targeting and Compatibility.

备注

通过通知中心,设备可使用同一标记注册多个模板。With Notification Hubs, a device can register multiple templates by using the same tag. 在这种情况下,针对该标签的传入的邮件将导致系统向设备发送多个通知(每个通知对应一个模板)。In this case, an incoming message that targets the tag results in multiple notifications being delivered to the device, one for each template. 此过程可以在多个可视通知中显示同一消息,如显示为 Windows 应用商店应用中的徽章和 toast 通知。This process enables you to display the same message in multiple visual notifications, such as both as a badge and as a toast notification in a Windows Store app.

使用模板发送跨平台通知Send cross-platform notifications using templates

本部分使用了你在使用 Azure 通知中心向特定用户发送通知教程中构建的示例代码。This section uses the sample code you built in the Send notifications to specific users by using Azure Notification Hubs tutorial. 可以从 GitHub 下载该示例。You can download the sample from GitHub.

若要使用模板发送跨平台通知,请执行以下步骤:To send cross-platform notifications by using templates, do the following steps:

  1. 在 Visual Studio 的“解决方案资源管理器”中,展开“Controllers”文件夹,然后打开 RegisterController.cs 文件。 In Visual Studio in Solution Explorer, expand the Controllers folder, and then open the RegisterController.cs file.

  2. Put 方法中找到用于创建新注册的代码块,然后将 switch 内容替换为以下代码:Locate the block of code in the Put method that creates a new registration, and then replace the switch content with the following code:

    switch (deviceUpdate.Platform)
    {
        case "mpns":
            var toastTemplate = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<wp:Notification xmlns:wp=\"WPNotification\">" +
                    "<wp:Toast>" +
                        "<wp:Text1>$(message)</wp:Text1>" +
                    "</wp:Toast> " +
                "</wp:Notification>";
            registration = new MpnsTemplateRegistrationDescription(deviceUpdate.Handle, toastTemplate);
            break;
        case "wns":
            toastTemplate = @"<toast><visual><binding template=""ToastText01""><text id=""1"">$(message)</text></binding></visual></toast>";
            registration = new WindowsTemplateRegistrationDescription(deviceUpdate.Handle, toastTemplate);
            break;
        case "apns":
            var alertTemplate = "{\"aps\":{\"alert\":\"$(message)\"}}";
            registration = new AppleTemplateRegistrationDescription(deviceUpdate.Handle, alertTemplate);
            break;
        default:
            throw new HttpResponseException(HttpStatusCode.BadRequest);
    }
    

    此代码调用平台特定的方法来创建模板注册而非本机注册。This code calls the platform-specific method to create a template registration instead of a native registration. 由于模板注册派生自本机注册,因此无需修改现有注册。Because template registrations derive from native registrations, you don't need to modify existing registrations.

  3. 在“解决方案资源管理器”的“Controllers”文件夹中,打开“NotificationsController.cs”文件。 In Solution Explorer, in the Controllers folder, open the NotificationsController.cs file. Post 方法替换为以下代码:Replace the Post method with the following code:

    public async Task<HttpResponseMessage> Post()
    {
        var user = HttpContext.Current.User.Identity.Name;
        var userTag = "username:" + user;
    
        var notification = new Dictionary<string, string> { { "message", "Hello, " + user } };
        await Notifications.Instance.Hub.SendTemplateNotificationAsync(notification, userTag);
    
        return Request.CreateResponse(HttpStatusCode.OK);
    }
    

    此代码将通知同时发送到所有平台。This code sends a notification to all platforms at the same time. 不指定本机有效负载。You don't specify a native payload. 通知中心会使用所提供的标记值(在注册的模板中指定)生成正确的负载并将它传递到每个设备。Notification Hubs builds and delivers the correct payload to every device with the provided tag value, as specified in the registered templates.

  4. 重新发布 Web API 项目。Republish your Web API project.

  5. 再次运行客户端应用来验证注册是否已成功。Run the client app again to verify that the registration has succeeded.

  6. 可以选择将客户端应用部署到另一个设备,然后运行该应用。Optionally, deploy the client app to a second device, and then run the app. 通知会显示在每个设备上。A notification is displayed on each device.

后续步骤Next steps

现在,你已完成本教程,可以查看以下文章来详细了解通知中心和模板:Now that you've completed this tutorial, find out more about Notification Hubs and templates in these articles: