使用通知中心向用户发送跨平台通知Send cross-platform notifications to users with Notification Hubs

在上一教程使用通知中心通知用户中,我们了解了如何向注册给经过身份验证的特定用户的所有设备推送通知。In a previous tutorial, Notify users with Notification Hubs, you learned how to push notifications to all devices that are registered to a specific authenticated user. 在该教程中,需要使用多个请求将通知发送到每个支持的客户端平台。In that tutorial, multiple requests were required 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, in a single request, a platform-agnostic notification that targets all platforms. 有关模板的更多详细信息,请参阅 Azure 通知中心概述For more detailed information about templates, see Azure Notification Hubs Overview.

重要

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

备注

通过通知中心,设备可使用同一标记注册多个模板。With Notification Hubs, a device can register multiple templates with the same tag. 在这种情况下,针对该标签的传入的邮件将导致系统向设备发送多个通知(每个通知对应一个模板)。In this case, an incoming message that targets the tag results in multiple notifications 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

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

  1. 在 Visual Studio 的解决方案资源管理器中,展开“控制器”文件夹,然后打开 RegisterController.cs 文件。 In the Solution Explorer in Visual Studio, 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. Notifications 控制器中,将 sendNotification 方法替换为以下代码:In the Notifications controller, replace the sendNotification 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, without you are having to 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. 重新发布 WebApi 后端项目。Republish your WebApi back-end project.

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

  6. (可选)将客户端应用部署到第二个设备,然后运行该应用。(Optional) 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 have completed this tutorial, find out more about Notification Hubs and templates in these topics: