c# - 尝试向 Azure 通知中心注册 Xamarin 应用程序时出现未经授权的异常

标签 c# azure xamarin google-cloud-messaging azure-notificationhub

我们正在尝试使用 Azure 通知中心通过 GCM/Firebase 将推送通知传递到 Xamarin Forms 应用程序。

这是我们用来在 PCL 中创建 MobileServiceClient 对象的代码:

public App()
{
    mobileServiceClient = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient("https://namespace.servicebus.windows.net/NotificationHubName", new ModernHttpClient.NativeMessageHandler());
}

据我了解文档,我们不使用自定义 HTTP 处理程序并不重要,因为我们不需要提供任何额外的 header 或类似的内容。我们只需要通知,此时不需要 Azure 提供身份验证(我们使用 Azure Active Directory B2C)。但我可能是错的,因为缺少身份验证 header 显然可能会导致未经授权的异常。

这是我们用来尝试向 Azure 通知中心注册我们的应用程序的代码:

public async void Register(Microsoft.WindowsAzure.MobileServices.Push push, IEnumerable<string> tags)
{
    try
    {
        const string templateBodyGCM = "{\"data\":{\"message\":\"$(messageParam)\"}}";

        JObject templates = new JObject();
        templates["genericMessage"] = new JObject
        {
            {"body", templateBodyGCM}
        };

        await push.RegisterAsync(RegistrationID, templates);
        Log.Info("Push Installation Id", push.InstallationId.ToString());
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine(ex.Message);
        Debugger.Break();
    }
}

不幸的是,await push.RegisterAsync(RegistrationID, templates) 中抛出异常:

{Microsoft.WindowsAzure.MobileServices.MobileServiceInvalidOperationException: The request could not be completed.  (Unauthorized)

我们成功从 GCM 收到注册 ID,并在尝试向 Azure 注册我们的应用程序以接收推送通知时遇到异常。

不幸的是,大多数有关通知中心的示例都使用旧代码,不需要 MobileServiceClient 构造函数中的第二个参数。该代码基于此存储库:https://github.com/xamarin/xamarin-forms-samples/tree/master/WebServices/TodoAzurePush

预先感谢您的帮助!

编辑:测试设备上打开了日期/时间同步。这似乎给其他开发者带来了类似的问题,但似乎不是这里的问题。

最佳答案

mobileServiceClient = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient("https://namespace.servicebus.windows.net/NotificationHubName", new ModernHttpClient.NativeMessageHandler());

根据您的描述和错误,我发现您向MobileServiceClient对象传递了错误的url参数。

Microsoft.WindowsAzure.MobileServices.MobileServiceClient 的 URL 是您的移动应用的 URL,而不是通知中心 URL。

如下:

mobileServiceClient = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient("http://yourmobileappname.azurewebsites.net", new ModernHttpClient.NativeMessageHandler());

在移动服务门户中设置与通知中心的连接后,azure mobile SDK将自动根据正确的MobileServiceClient获取推送对象。

我建议您还可以检查您是否已连接到移动应用程序中的通知中心,如下所示:

enter image description here

关于c# - 尝试向 Azure 通知中心注册 Xamarin 应用程序时出现未经授权的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44395331/

相关文章:

c# - 什么时候(不)两个具有相同内容的字符串共享相同的内存?

azure - 无法获取 Azure 成本消耗 api 的 Azure 范围

android - Xamarin Forms Android 应用程序在使用 VS Android 模拟器运行调试时崩溃

c# - 具有可绑定(bind)属性的自定义 View 未在 Xamarin.Forms SAP 上正确绑定(bind)

c# - VS2012 导出 "User Settings"

c# - 红外传感器和RGB图像的Kinect v2对齐始终略有偏离

C# 获取类型() : Code how to get the type of T in List<T> without actual elements?

azure - Terraform 单变量问题的多个值

.net - Windows Azure REST Api 背后的技术是什么?

c# - 是否可以将 Xaml 设计器或智能感知与 Xamarin.Forms 一起使用?