通过通知中心向所有用户发送推送通知

时间:2018-03-18 19:26:16

标签: azure asp.net-web-api push-notification azure-notificationhub

我一直试图弄清楚如何在我的asp.net web api中发送推送通知。我看到有方法可以通过设备本身和后端在集线器中注册设备。我想使用第一种方法,并找到了一些教程,但我不知道如何从后端发送请求。我尝试了以下代码,但它给了我401 Unauthorized错误:

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

如果有人能指点我,我会感激不尽。我正在寻找一个解决方案......

1 个答案:

答案 0 :(得分:0)

  

但我不知道如何从后端发送请求。我尝试了以下代码,但它给了我401 Unauthorized错误

根据您的说明,您使用 Microsoft.Azure.NotificationHubs进行Microsoft Azure通知中心后端操作。

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

我建议您在通过方法NotificationHubClient构建CreateClientFromConnectionString时检查通知Hub Connection,并确保连接字符串具有正确的完全访问权限。您可以使用上面的nuget包创建一个控制台应用程序来发送通知,并使用fiddler捕获详细的错误响应以缩小此问题的范围。此外,您可以关注Diagnose dropped notifications in Notification Hubs