从 .Net 核心服务连接到 AzureNotificationHub 时如何设置代理

How to set the proxy when connecting to AzureNotificationHub from a .Net core service

我想知道以前是否有人处理过这种情况。我们有一个 .NET core 2.1 API 需要连接到 AzureNotificationHub 来发送一些推送通知。

我们正在使用 Microsoft 的 NotificationHubClient 库 (nuget "microsoft azure notification hubs" v2.0.1)。除了我们需要配置代理的生产环境外,它在所有环境中都能正常工作。这个库似乎没有提供明确设置代理的方法。

为了让它更有趣,在 .NET 核心内部显然设置用于所有传出请求的默认 Web 代理也不起作用。

        WebRequest.DefaultWebProxy = new WebProxy(configuration.GetValue<string>("WebServices:Proxy"));
        WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;

有一些方法可以通过 "middleware" 类型的解决方案在 Kestrel 管道中注入代理,但它们似乎都假设通信将由 HttpClient 完成。当我们需要使用一个封闭的库时会发生什么?

非常感谢任何帮助

在 microsoft.azure.notification.hubs 的 3.0.0 版本中,class NotificationHubClient 有一个接收 NotificationHubClientSettings 类型对象的构造函数,您可以使用此对象来配置将传递的 HttpMessageHandler 或 Proxy到 NotificationHubClient 对象创建的 HttpClient。

这是配置代理的示例代码:

NotificationHubClientSettings settings = new NotificationHubClientSettings();
settings.Proxy = new WebProxy("1.1.1.1",8080)
NotificationHubClient client = new NotificationHubClient("hubconnectionstring", "hubnotificationpath", settings);    

希望这对您有所帮助,如果您想查看可以使用的其他选项,我建议您查看 github (https://github.com/Azure/azure-notificationhubs-dotnet/blob/master/src/Microsoft.Azure.NotificationHubs/NotificationHubClient.cs) 上的源代码。