您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

适用于 Azure Functions 的 通知中心输出绑定Notification Hubs output binding for Azure Functions

本文介绍如何在 Azure Functions 中使用 Azure 通知中心绑定发送推送通知。This article explains how to send push notifications by using Azure Notification Hubs bindings in Azure Functions. Azure Functions 支持通知中心的输出绑定。Azure Functions supports output bindings for Notification Hubs.

必须为想要使用的平台通知服务 (PNS) 配置 Azure 通知中心。Azure Notification Hubs must be configured for the Platform Notifications Service (PNS) you want to use. 若要了解如何从通知中心获取客户端应用程序中的推送通知,请参阅通知中心入门,并从页面顶部附近的下拉列表中选择目标客户端平台。To learn how to get push notifications in your client app from Notification Hubs, see Getting started with Notification Hubs and select your target client platform from the drop-down list near the top of the page.

此参考信息面向 Azure Functions 开发人员。This is reference information for Azure Functions developers. Azure Functions 的新手请从以下资源入手:If you're new to Azure Functions, start with the following resources:

重要

Google 已不推荐使用 Google Cloud Messaging (GCM) 以支持 Firebase Cloud Messaging (FCM)Google has deprecated Google Cloud Messaging (GCM) in favor of Firebase Cloud Messaging (FCM). 此输出绑定不支持 FCM。This output binding doesn't support FCM. 发送使用 FCM 的通知,请使用Firebase API直接在函数或使用模板通知To send notifications using FCM, use the Firebase API directly in your function or use template notifications.

包 - Functions 1.xPackages - Functions 1.x

Microsoft.Azure.WebJobs.Extensions.NotificationHubs NuGet 包 1.x 版中提供了通知中心绑定。The Notification Hubs bindings are provided in the Microsoft.Azure.WebJobs.Extensions.NotificationHubs NuGet package, version 1.x. azure-webjobs-sdk-extensions GitHub 存储库中提供了此包的源代码。Source code for the package is in the azure-webjobs-sdk-extensions GitHub repository.

下表说明了如何在每个开发环境中添加对此绑定的支持。The following table tells how to add support for this binding in each development environment.

开发环境Development environment 添加支持To add support in
Functions 1.xFunctions 1.x
本地开发 - C# 类库Local development - C# class library 安装包Install the package
本地开发 - C# 脚本、JavaScript、F#Local development - C# script, JavaScript, F# 自动Automatic
门户开发Portal development 自动Automatic

包 - Functions 2.xPackages - Functions 2.x

此绑定在 Functions 2.x 中不可用。This binding is not available in Functions 2.x.

示例 - 模板Example - template

发送的通知可为本机通知,或者模板通知The notifications you send can be native notifications or template notifications. 本机通知面向在输出绑定的 platform 属性中配置的特定客户端平台。Native notifications target a specific client platform as configured in the platform property of the output binding. 模板通知可用于面向多个平台。A template notification can be used to target multiple platforms.

参阅语言特定的示例:See the language-specific example:

C# 脚本模板示例 - out 参数C# script template example - out parameter

此示例发送一条在模板中包含 message 占位符的模板注册通知。This example sends a notification for a template registration that contains a message placeholder in the template.

using System;
using System.Threading.Tasks;
using System.Collections.Generic;

public static void Run(string myQueueItem,  out IDictionary<string, string> notification, TraceWriter log)
{
    log.Info($"C# Queue trigger function processed: {myQueueItem}");
    notification = GetTemplateProperties(myQueueItem);
}

private static IDictionary<string, string> GetTemplateProperties(string message)
{
    Dictionary<string, string> templateProperties = new Dictionary<string, string>();
    templateProperties["message"] = message;
    return templateProperties;
}

C# 脚本模板示例 - 异步C# script template example - asynchronous

如果使用的是异步代码,则不允许使用 out 参数。If you are using asynchronous code, out parameters are not allowed. 在此情况下,使用 IAsyncCollector 返回模板通知。In this case use IAsyncCollector to return your template notification. 以下代码是上述代码的异步示例。The following code is an asynchronous example of the code above.

using System;
using System.Threading.Tasks;
using System.Collections.Generic;

public static async Task Run(string myQueueItem, IAsyncCollector<IDictionary<string,string>> notification, TraceWriter log)
{
    log.Info($"C# Queue trigger function processed: {myQueueItem}");

    log.Info($"Sending Template Notification to Notification Hub");
    await notification.AddAsync(GetTemplateProperties(myQueueItem));    
}

private static IDictionary<string, string> GetTemplateProperties(string message)
{
    Dictionary<string, string> templateProperties = new Dictionary<string, string>();
    templateProperties["user"] = "A new user wants to be added : " + message;
    return templateProperties;
}

C# 脚本模板示例 - JSONC# script template example - JSON

此示例使用有效的 JSON 字符串,发送一条在模板中包含 message 占位符的模板注册通知。This example sends a notification for a template registration that contains a message placeholder in the template using a valid JSON string.

using System;

public static void Run(string myQueueItem,  out string notification, TraceWriter log)
{
    log.Info($"C# Queue trigger function processed: {myQueueItem}");
    notification = "{\"message\":\"Hello from C#. Processed a queue item!\"}";
}

C# 脚本模板示例 - 库类型C# script template example - library types

此示例演示如何使用 Microsoft Azure 通知中心库中定义的类型。This example shows how to use types defined in the Microsoft Azure Notification Hubs Library.

#r "Microsoft.Azure.NotificationHubs"

using System;
using System.Threading.Tasks;
using Microsoft.Azure.NotificationHubs;

public static void Run(string myQueueItem,  out Notification notification, TraceWriter log)
{
   log.Info($"C# Queue trigger function processed: {myQueueItem}");
   notification = GetTemplateNotification(myQueueItem);
}

private static TemplateNotification GetTemplateNotification(string message)
{
    Dictionary<string, string> templateProperties = new Dictionary<string, string>();
    templateProperties["message"] = message;
    return new TemplateNotification(templateProperties);
}

F # 模板示例F# template example

此示例发送一条包含 locationmessage模板注册的通知。This example sends a notification for a template registration that contains location and message.

let Run(myTimer: TimerInfo, notification: byref<IDictionary<string, string>>) =
    notification = dict [("location", "Redmond"); ("message", "Hello from F#!")]

JavaScript 模板示例JavaScript template example

此示例发送一条包含 locationmessage模板注册的通知。This example sends a notification for a template registration that contains location and message.

module.exports = function (context, myTimer) {
    var timeStamp = new Date().toISOString();

    if (myTimer.IsPastDue)
    {
        context.log('Node.js is running late!');
    }
    context.log('Node.js timer trigger function ran!', timeStamp);  
    context.bindings.notification = {
        location: "Redmond",
        message: "Hello from Node!"
    };
    context.done();
};

示例 - APNS 本机通知Example - APNS native

此 C# 脚本示例演示如何发送 APNS 本机通知。This C# script example shows how to send a native APNS notification.

#r "Microsoft.Azure.NotificationHubs"
#r "Newtonsoft.Json"

using System;
using Microsoft.Azure.NotificationHubs;
using Newtonsoft.Json;

public static async Task Run(string myQueueItem, IAsyncCollector<Notification> notification, TraceWriter log)
{
    log.Info($"C# Queue trigger function processed: {myQueueItem}");

    // In this example the queue item is a new user to be processed in the form of a JSON string with 
    // a "name" value.
    //
    // The JSON format for a native APNS notification is ...
    // { "aps": { "alert": "notification message" }}  

    log.LogInformation($"Sending APNS notification of a new user");    
    dynamic user = JsonConvert.DeserializeObject(myQueueItem);    
    string apnsNotificationPayload = "{\"aps\": {\"alert\": \"A new user wants to be added (" + 
                                        user.name + ")\" }}";
    log.LogInformation($"{apnsNotificationPayload}");
    await notification.AddAsync(new AppleNotification(apnsNotificationPayload));        
}

示例 - WNS 本机通知Example - WNS native

此 C# 脚本示例演示如何使用 Microsoft Azure 通知中心库中定义的类型发送本机 WNS toast 通知。This C# script example shows how to use types defined in the Microsoft Azure Notification Hubs Library to send a native WNS toast notification.

#r "Microsoft.Azure.NotificationHubs"
#r "Newtonsoft.Json"

using System;
using Microsoft.Azure.NotificationHubs;
using Newtonsoft.Json;

public static async Task Run(string myQueueItem, IAsyncCollector<Notification> notification, TraceWriter log)
{
    log.Info($"C# Queue trigger function processed: {myQueueItem}");

    // In this example the queue item is a new user to be processed in the form of a JSON string with 
    // a "name" value.
    //
    // The XML format for a native WNS toast notification is ...
    // <?xml version="1.0" encoding="utf-8"?>
    // <toast>
    //      <visual>
    //     <binding template="ToastText01">
    //       <text id="1">notification message</text>
    //     </binding>
    //   </visual>
    // </toast>

    log.Info($"Sending WNS toast notification of a new user");    
    dynamic user = JsonConvert.DeserializeObject(myQueueItem);    
    string wnsNotificationPayload = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                    "<toast><visual><binding template=\"ToastText01\">" +
                                        "<text id=\"1\">" + 
                                            "A new user wants to be added (" + user.name + ")" + 
                                        "</text>" +
                                    "</binding></visual></toast>";

    log.Info($"{wnsNotificationPayload}");
    await notification.AddAsync(new WindowsNotification(wnsNotificationPayload));        
}

属性Attributes

C# 类库中,使用 NotificationHub 特性。In C# class libraries, use the NotificationHub attribute.

配置部分描述了该特性的构造函数参数和属性。The attribute's constructor parameters and properties are described in the configuration section.

配置Configuration

下表解释了在 function.json 文件和 NotificationHub 特性中设置的绑定配置属性:The following table explains the binding configuration properties that you set in the function.json file and the NotificationHub attribute:

function.json 属性function.json property Attribute 属性Attribute property 说明Description
类型type 不适用n/a 必须设置为“notificationHub”。Must be set to "notificationHub".
directiondirection 不适用n/a 必须设置为“out”。Must be set to "out".
namename 不适用n/a 在通知中心消息的函数代码中使用的变量名。Variable name used in function code for the notification hub message.
tagExpressiontagExpression TagExpressionTagExpression 标记表达式允许指定将通知传递到一组已注册接收通知的与标记表达式匹配的设备。Tag expressions allow you to specify that notifications be delivered to a set of devices that have registered to receive notifications that match the tag expression. 有关详细信息,请参阅路由和标记表达式For more information, see Routing and tag expressions.
hubNamehubName HubNameHubName 在 Azure 门户中通知中心资源的名称。Name of the notification hub resource in the Azure portal.
连接connection ConnectionStringSettingConnectionStringSetting 包含通知中心连接字符串的应用设置的名称。The name of an app setting that contains a Notification Hubs connection string. 连接字符串必须设置为通知中心的 DefaultFullSharedAccessSignature 值。The connection string must be set to the DefaultFullSharedAccessSignature value for your notification hub. 请参阅本文稍后的连接字符串设置部分。See Connection string setup later in this article.
platformplatform 平台Platform 平台属性指示通知面向的客户端平台。The platform property indicates the client platform your notification targets. 默认情况下,如果从输出绑定中省略平台属性,则模板通知可用于面向 Azure 通知中心上配置的任何平台。By default, if the platform property is omitted from the output binding, template notifications can be used to target any platform configured on the Azure Notification Hub. 有关一般情况下使用模板通过 Azure 通知中心发送跨平台通知的详细信息,请参阅模板For more information on using templates in general to send cross platform notifications with an Azure Notification Hub, see Templates. 进行设置时,platform 必须是以下值之一:When set, platform must be one of the following values:

在本地进行开发时,应用设置将取 local.settings.json 文件的值。When you're developing locally, app settings go into the local.settings.json file.

function.json 文件示例function.json file example

下面是 function.json 文件中某个通知中心绑定的示例。Here's an example of a Notification Hubs binding in a function.json file.

{
  "bindings": [
    {
      "type": "notificationHub",
      "direction": "out",
      "name": "notification",
      "tagExpression": "",
      "hubName": "my-notification-hub",
      "connection": "MyHubConnectionString",
      "platform": "apns"
    }
  ],
  "disabled": false
}

连接字符串设置Connection string setup

若要使用通知中心输出绑定,必须配置中心的连接字符串。To use a notification hub output binding, you must configure the connection string for the hub. 可以选择现有通知中心,也可以在 Azure 门户中通过“集成”选项卡创建一个新的通知中心。You can select an existing notification hub or create a new one right from the Integrate tab in the Azure portal. 还可以手动配置连接字符串。You can also configure the connection string manually.

配置现有通知中心的连接字符串:To configure the connection string to an existing notification hub:

  1. 导航到 Azure 门户中的通知中心,选择“访问策略”,然后选择 DefaultFullSharedAccessSignature 策略旁边的复制按钮。Navigate to your notification hub in the Azure portal, choose Access policies, and select the copy button next to the DefaultFullSharedAccessSignature policy. 这会将 DefaultFullSharedAccessSignature 策略的连接字符串复制到通知中心。This copies the connection string for the DefaultFullSharedAccessSignature policy to your notification hub. 此连接字符串可让函数将通知消息发送到中心。This connection string lets your function send notification messages to the hub. 复制通知中心连接字符串Copy the notification hub connection string
  2. 导航到 Azure 门户中的函数应用,选择“应用程序设置”,添加一个键(例如 MyHubConnectionString),粘贴复制的 DefaultFullSharedAccessSignature 作为通知中心的值,然后单击“保存”。Navigate to your function app in the Azure portal, choose Application settings, add a key such as MyHubConnectionString, paste the copied DefaultFullSharedAccessSignature for your notification hub as the value, and then click Save.

此应用程序设置的名称将传入 function.json 中的输出绑定连接设置或 .NET 特性。The name of this application setting is what goes in the output binding connection setting in function.json or the .NET attribute. 请参阅本文前面的配置部分See the Configuration section earlier in this article.

在本地进行开发时,应用设置将取 local.settings.json 文件的值。When you're developing locally, app settings go into the local.settings.json file.

异常和返回代码Exceptions and return codes

绑定Binding 参考Reference
通知中心Notification Hub 操作指南Operations Guide

后续步骤Next steps