简体   繁体   中英

Failing to deliver Azure NotificationHub push messages to (Android) devices from .NET console app

I have configured a .NET App Service using the "Quick Start" instructions in the newer Azure Portal to publish an app service to use as my mobile back end. I have also configured a notification hub for it and am able to send push notifications from a Xamarin.Forms Android app via the Azure mobile back end endpoint. I can also receive the push notification on a registered Android device.

I need to be able to send push notifications to registered devices from a C# console application but no matter what I try, the push messages are not delivered.

I am using the following code to attempt to send push messages. When I run it, the execution ends on...

 var result = await hub.SendTemplateNotificationAsync(templateParams);

...and console app terminates without waiting for the response and the push notification is never delivered to the registered device.

public async void PushSmartAlerts()
{
    string notificationHubName = "DevXXXXNotificationHub";
    string notificationHubConnection = "Endpoint=sb://devXXXXXnotificationhubnamespace.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=SnXXXXXXXXXXXXXXXXXXXXXXXX9N8=";
    hub = NotificationHubClient .CreateClientFromConnectionString(notificationHubConnection, notificationHubName);
    Dictionary<string, string> templateParams = new Dictionary<string, string>();
    templateParams["messageParam"] = "Hello";
        var result = await hub.SendTemplateNotificationAsync(templateParams);
}

Can anyone tell me what is wrong or if I am going about it the wrong way?

Solved it. There was nothing wrong with the way I was using the NotificationHubClient to create and send the notification. The reason it was not working is that Console applications do not support await in the Main method so execution was ending before the push notification could be sent. By changing the code to the following, the push notification was sent and delivered.

   string notificationHubName = "xxxxxxx";
    string notificationHubConnection = "Endpoint=sb://xxxxxx";
     hub = NotificationHubClient.CreateClientFromConnectionString(notificationHubConnection, notificationHubName, true);
    Dictionary<string, string> notification = new Dictionary<string, string>()
    {
        {"messageParam", "It works. Tap to view."}
    };
    var task = hub.SendTemplateNotificationAsync(notification);
    task.Wait();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM