英語で読む

次の方法で共有

适用于 Azure Functions 的 Azure 通知中心输出绑定

本文介绍如何在 Azure Functions 中使用 Azure 通知中心 绑定发送推送通知。 Azure Functions 支持通知中心的输出绑定。

必须为想要使用的平台通知服务 (PNS) 配置通知中心。 有关如何从通知中心获取客户端应用中的推送通知的详细信息,请参阅 快速入门:在通知中心设置推送通知

包:Functions 1.x

通知中心绑定在 Microsoft.Azure.WebJobs.Extensions.NotificationHubs NuGet 包 1.x 版中提供。 包的源代码位于 azure-webjobs-sdk-extensions GitHub 存储库中。

下表说明了如何在每个开发环境中添加对此绑定的支持。

开发环境 添加支持
Functions 1.x
本地开发 - C# 类库 安装包
本地开发 - C# 脚本、JavaScript、F# 自动
门户开发 自动

包:Functions 2.x 及更高版本

输出绑定在 Functions 2.x 及更高版本中不可用。

示例模板:

发送的通知可以是本机通知或 模板通知。 本机通知面向在输出绑定的 platform 属性中配置的特定客户端平台。 模板通知可用于面向多个平台。

每种语言的模板示例:

C# 脚本模板示例:out 参数

此示例发送一条在模板中包含 占位符的message通知:

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# 脚本模板示例:异步

如果使用的是异步代码,则不允许使用 out 参数。 在此情况下,使用 IAsyncCollector 返回模板通知。 以下代码是上一示例的异步示例:

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# 脚本模板示例:JSON

此示例使用有效的 JSON 字符串,发送一条在模板中包含 占位符的message通知:

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# 脚本模板示例:库类型

此示例演示如何使用 Azure 通知中心库中定义的类型:

#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 # 模板示例

此示例发送一条包含 locationmessage的通知:

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

JavaScript 模板示例

此示例发送一条包含 locationmessage的通知:

module.exports = async 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!"
    };
};

示例:APNS 本机通知

此 C# 脚本示例演示如何发送本机 Apple Push Notification 服务 (APNS) 通知:

#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 Apple Push Notification Service (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 本机通知

此 C# 脚本示例演示如何使用 Azure 通知中心库中 定义的类型发送本机 Windows 推送通知服务 (WNS) Toast 通知:

#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));        
}

特性

C# 类库中,使用 NotificationHub 属性。

属性的构造函数参数和属性在 “配置” 部分介绍。

配置

下表列出了在 function.json 文件和 NotificationHub 特性中设置的绑定配置属性:

function.json 属性 Attribute 属性 说明
类型 不适用 设置为 notificationHub
direction 不适用 设置为 out
名字 不适用 在通知中心消息的函数代码中使用的变量名。
tagExpression TagExpression 标记表达式允许指定将通知传递到一组已注册接收通知的与标记表达式匹配的设备。 有关详细信息,请参阅 路由和标记表达式
hubName HubName 在 Azure 门户中通知中心资源的名称。
连接 ConnectionStringSetting 包含通知中心连接字符串的应用设置的名称。 将连接字符串设置为通知中心的 DefaultFullSharedAccessSignature 值。 有关详细信息,请参阅 连接字符串设置

在本地开发时,请在集合中的 local.settings.json 文件中Values添加应用程序设置。

function.json 文件示例

下面是 function.json 文件中通知中心绑定的示例:

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

连接字符串设置

若要使用通知中心输出绑定,必须配置中心的连接字符串。

重要

通知中心绑定不支持Microsoft Entra 身份验证和托管标识。 可以使用 Azure 密钥库集中管理通知中心连接字符串并帮助进行密钥轮换。 若要了解详细信息,请参阅 “管理连接”。

可以选择现有通知中心,也可以在 Azure 门户中通过“集成”选项卡创建一个新的通知中心。 还可以手动配置连接字符串。

配置现有通知中心的连接字符串:

  1. 导航到 Azure 门户中的通知中心,选择 “访问策略”,然后选择 DefaultFullSharedAccessSignature 策略旁边的复制按钮。

    DefaultFullSharedAccessSignature 策略的连接字符串会复制到通知中心。 此连接字符串可让函数将通知消息发送到中心。 显示如何复制通知中心连接字符串的屏幕截图。

  2. 在 Azure 门户中导航到函数应用,展开“设置”,然后选择“环境变量”

  3. 在“应用设置”选项卡中,选择“+ 添加”以添加键,例如 MyHubConnectionString。 此应用设置的“名称”是 function.json 中的输出绑定连接设置或 .NET 特性。 有关详细信息,请参阅 “配置”。

  4. 对于值,请粘贴从通知中心复制的 DefaultFullSharedAccessSignature 连接字符串,然后选择“应用”

在本地开发时,请在集合中的 local.settings.json 文件中Values添加应用程序设置。

异常和返回代码

绑定 参考
通知中心 作指南