Share via


Uitvoerbindingen voor Azure Notification Hubs voor Azure Functions

In dit artikel wordt uitgelegd hoe u pushmeldingen verzendt met behulp van Azure Notification Hubs-bindingen in Azure Functions. Azure Functions ondersteunt uitvoerbindingen voor Notification Hubs.

U moet Notification Hubs configureren voor de PNS (Platform Notifications Service) die u wilt gebruiken. Zie Quickstart: Pushmeldingen instellen in een Notification Hubs voor meer informatie over het ontvangen van pushmeldingen in uw client-app.

Belangrijk

Google heeft Google Google Cloud Messaging (GCM) afgeschaft ten gunste van Firebase Cloud Messaging (FCM). Uitvoerbindingen voor Notification Hubs bieden echter geen ondersteuning voor FCM. Als u meldingen wilt verzenden met FCM, gebruikt u de Firebase-API rechtstreeks in uw functie of gebruikt u sjabloonmeldingen.

Pakketten: Functions 1.x

De Notification Hubs-bindingen worden geleverd in het NuGet-pakket Microsoft.Azure.WebJobs.Extensions.NotificationHubs , versie 1.x. De broncode voor het pakket bevindt zich in de GitHub-opslagplaats azure-webjobs-sdk-extensions .

De volgende tabel bevat informatie over het toevoegen van ondersteuning voor uitvoerbinding in elke ontwikkelomgeving.

Ontwikkelomgeving Ondersteuning toevoegen in Functions 1.x
Lokale ontwikkeling: C#-klassebibliotheek Het pakket installeren
Lokale ontwikkeling: C#-script, JavaScript, F# Automatisch
Portal-ontwikkeling Automatisch

Pakketten: Functions 2.x en hoger

Uitvoerbinding is niet beschikbaar in Functions 2.x en hoger.

Voorbeeld van sjabloon:

De meldingen die u verzendt, kunnen systeemeigen meldingen of sjabloonmeldingen zijn. Een systeemeigen melding is gericht op een specifiek clientplatform, zoals geconfigureerd in de platform eigenschap van de uitvoerbinding. Een sjabloonmelding kan worden gebruikt om meerdere platforms te targeten.

Sjabloonvoorbeelden voor elke taal:

Voorbeeld van C#-scriptsjabloon: out-parameter

In dit voorbeeld wordt een melding verzonden voor een sjabloonregistratie die een message tijdelijke aanduiding in de sjabloon bevat:

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

Voorbeeld van C#-scriptsjabloon: asynchroon

Als u asynchrone code gebruikt, zijn outparameters niet toegestaan. In dit geval gebruikt IAsyncCollector u om uw sjabloonmelding te retourneren. De volgende code is een asynchroon voorbeeld van het vorige voorbeeld:

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

Voorbeeld van C#-scriptsjabloon: JSON

In dit voorbeeld wordt een melding verzonden voor een sjabloonregistratie die een message tijdelijke aanduiding in de sjabloon bevat met behulp van een geldige JSON-tekenreeks:

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!\"}";
}

Voorbeeld van C#-scriptsjabloon: bibliotheektypen

In dit voorbeeld ziet u hoe u typen gebruikt die zijn gedefinieerd in de Microsoft Azure Notification Hubs-bibliotheek:

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

Voorbeeld van F#-sjabloon

In dit voorbeeld wordt een melding verzonden voor een sjabloonregistratie die het volgende bevat location en message:

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

Voorbeeld van JavaScript-sjabloon

In dit voorbeeld wordt een melding verzonden voor een sjabloonregistratie die het volgende bevat location en message:

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!"
    };
};

Voorbeeld: APNS native

In dit C#-voorbeeldscript ziet u hoe u een systeemeigen APNS-melding (Apple Push Notification Service) verzendt:

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

Voorbeeld: WNS native

In dit C#-voorbeeldscript ziet u hoe u typen gebruikt die zijn gedefinieerd in de Microsoft Azure Notification Hubs-bibliotheek om een systeemeigen WNS-pop-upmelding (Windows Push Notification Service) te verzenden:

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

Kenmerken

Gebruik in C#-klassebibliotheken het kenmerk NotificationHub .

De constructorparameters en eigenschappen van het kenmerk worden beschreven in de sectie Configuratie .

Configuratie

De volgende tabel bevat de bindingsconfiguratie-eigenschappen die u hebt ingesteld in het function.json-bestand en het NotificationHub kenmerk:

function.json-eigenschap Kenmerkeigenschap Beschrijving
type N.v.t. Ingesteld op notificationHub.
direction N.v.t. Ingesteld op out.
name N.v.t. Variabelenaam die wordt gebruikt in functiecode voor het notification hub-bericht.
tagExpression TagExpression Met tagexpressies kunt u opgeven dat meldingen worden bezorgd op een set apparaten die zijn geregistreerd om meldingen te ontvangen die overeenkomen met de tag-expressie. Zie Routerings- en tagexpressies voor meer informatie.
hubName HubName De naam van de Notification Hub-resource in Azure Portal.
verbinding ConnectionStringSetting De naam van een app-instelling die een Notification Hubs-verbindingsreeks bevat. Stel de verbindingsreeks in op de waarde DefaultFullSharedAccessSignature voor uw Notification Hub. Zie De installatie van verbindingsreeksen voor meer informatie.
perron Platform De platformeigenschap geeft het clientplatform aan dat uw meldingsdoelen zijn. Als de platformeigenschap wordt weggelaten uit de uitvoerbinding, kunnen sjabloonmeldingen standaard worden gebruikt om elk platform te richten dat is geconfigureerd op de Azure Notification Hub. Zie Notification Hubs-sjablonen voor meer informatie over het gebruik van sjablonen voor het verzenden van platformoverschrijdende meldingen met een Azure Notification Hub. Wanneer het platform is ingesteld, moet dit een van de volgende waarden zijn:

Wanneer u lokaal ontwikkelt, voegt u uw toepassingsinstellingen toe aan het local.settings.json-bestand in de Values verzameling.

voorbeeld van function.json bestand

Hier volgt een voorbeeld van een Notification Hubs-binding in een function.json-bestand :

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

Installatie van verbindingsreeks

Als u een notification hub-uitvoerbinding wilt gebruiken, moet u de verbindingsreeks voor de hub configureren. U kunt een bestaande Notification Hub selecteren of een nieuwe maken op het tabblad Integreren in Azure Portal. U kunt de verbindingsreeks ook handmatig configureren.

De verbindingsreeks configureren voor een bestaande Notification Hub:

  1. Navigeer naar uw Notification Hub in Azure Portal, kies Toegangsbeleid en selecteer de knop Kopiëren naast het defaultFullSharedAccessSignature-beleid.

    De verbindingsreeks voor het DefaultFullSharedAccessSignature-beleid wordt gekopieerd naar uw Notification Hub. Met deze verbindingsreeks kan uw functie meldingsberichten verzenden naar de hub. Schermopname van het kopiëren van de Notification Hub verbindingsreeks.

  2. Navigeer naar uw functie-app in Azure Portal, vouw Instellingen uit en selecteer vervolgens Omgevingsvariabelen.

  3. Selecteer + Toevoegen op het tabblad App-instelling om een sleutel toe te voegen, zoals MyHubConnectionString. De naam van deze app-instelling is de verbindingsinstelling voor uitvoerbinding in function.json of het .NET-kenmerk. Zie Configuratie voor meer informatie.

  4. Plak voor de waarde de gekopieerde DefaultFullSharedAccessSignature-verbindingsreeks uit uw Notification Hub en selecteer Vervolgens Toepassen.

Wanneer u lokaal ontwikkelt, voegt u uw toepassingsinstellingen toe aan het local.settings.json-bestand in de Values verzameling.

Uitzonderingen en retourcodes

Binding Verwijzing
Notification Hub Operations Guide (Bedieningshandleiding)