Nadav Kratz
Nadav Kratz

Reputation: 1

Send push notification via notification hub to all users

I've been trying to figure out for a long time how to send a push notification in my asp.net web api. I saw that there are to ways to register a device in the hub, through the device itself and through the backend. I want to use the first method, and found some tutorial that does it, but I don't know how to send the request from the backend. I tried the following code, but it gives me 401 Unauthorized error:

[HttpGet]
    public async Task<HttpResponseMessage> NotTry()
    {
        NotificationOutcome outcome;
        HttpStatusCode ret = HttpStatusCode.InternalServerError;
        string notif = "{ \"data\" : {\"message\":\"hello\"}}";
        outcome = await Notifications.Instance.Hub.SendGcmNativeNotificationAsync(notif);
        if (outcome != null)
        {
            if (!((outcome.State == NotificationOutcomeState.Abandoned) ||
                (outcome.State == NotificationOutcomeState.Unknown)))
            {
                ret = HttpStatusCode.OK;
            }
        }

        return Request.CreateResponse(ret);
    }

If anyone could give me a direction, I'll be grateful. I am loosing my mind searching for a solution...

Upvotes: 0

Views: 607

Answers (1)

Bruce Chen
Bruce Chen

Reputation: 18465

but I don't know how to send the request from the backend. I tried the following code, but it gives me 401 Unauthorized error

According to your description, you are using the Microsoft.Azure.NotificationHubs for Microsoft Azure Notification Hubs back end operations.

NotificationHubClient Hub = NotificationHubClient.CreateClientFromConnectionString("<your hub's DefaultFullSharedAccessSignature>","<hub name>"); 
await hub.SendGcmNativeNotificationAsync("{payload}");

I would recommend you check the notification Hub Connection when constructing the NotificationHubClient via the method CreateClientFromConnectionString, and make sure the connection string has the correct full access. You could just create a console application using the above nuget package to send the notification and use the fiddler to capture the detailed error response to narrow down this issue. Moreover, you could follow Diagnose dropped notifications in Notification Hubs.

Upvotes: 1

Related Questions