firebase - 如何通过代理使用 FirebaseAdmin?

标签 firebase .net-core firebase-cloud-messaging

以下代码在本地运行得非常好。 当我通过本地 PC 发送时,用户会收到所有推送(通知)。 但我需要在服务器上使用代理,并且此代码会引发错误:“无法建立连接:网络无法访问”。 请帮我设置此代码的代理。

using System;
using MediatR;
using System.IO;
using FirebaseAdmin;
using System.Threading;
using System.Threading.Tasks;
using FirebaseAdmin.Messaging;
using Google.Apis.Auth.OAuth2;

namespace JMGlobal.Handlers
{
    public class PushHandler : IRequestHandler<Request_Push, Response_Push>
    {
        public async Task<Response_Push> Handle(Request_Push request, CancellationToken cancellationToken)
        {
            try
            {
                var defaultApp = FirebaseApp.DefaultInstance;

                if (defaultApp == null)
                {
                    var keyPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "jKey.json");
                    defaultApp = FirebaseApp.Create(new AppOptions()
                    {
                        Credential = GoogleCredential.FromFile(keyPath),
                        // HttpClientFactory --- ????
                    });
                }
                var message = new Message()
                {
                    Token = request.FirebaseToken,
                    Apns = new ApnsConfig()
                    {
                        Aps = new FirebaseAdmin.Messaging.Aps()
                        {
                            Alert = new ApsAlert()
                            {
                                Title = "push",
                                Body = request.PushMessage
                            }
                        }
                    },
                     Notification = new Notification
                    {
                        Title = "System Notification",
                        Body = $"Message: {request.PushMessage}"
                    }
                };
                var messaging = FirebaseMessaging.DefaultInstance;
                var result = await messaging.SendAsync(message); // here fires the error: "Failed to establish a connection: Network is unreachable"

                return new Response_Push()
                { .... };
            }
            catch (Exception ex)
            {..... }

        }
    }

}

最佳答案

工作版本如下。

using System;
using MediatR;
using System.IO;
using FirebaseAdmin;
using System.Threading;
using System.Diagnostics;
using System.Threading.Tasks;
using FirebaseAdmin.Messaging;
using Google.Apis.Auth.OAuth2;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Google.Apis.Http;
using System.Net.Http;
using System.Net;
using Microsoft.Extensions.Options;

namespace JMGlobal.Handlers
{
    public class ProxyHttpClientFactory2 : Google.Apis.Http.HttpClientFactory
    {
        private readonly string proxyAddress;
        private readonly bool proxyUseProxy;
        private readonly bool proxyBypassOnLocal;

        public ProxyHttpClientFactory2(string proxyAddress, bool proxyUseProxy, bool proxyBypassOnLocal)
        {
            this.proxyAddress = proxyAddress;
            this.proxyUseProxy = proxyUseProxy;
            this.proxyBypassOnLocal = proxyBypassOnLocal;
        }

        protected override HttpMessageHandler CreateHandler(CreateHttpClientArgs args)
        {
            var proxy = new WebProxy(Address: proxyAddress, BypassOnLocal: proxyBypassOnLocal, BypassList: null, Credentials: null);
            var webRequestHandler = new HttpClientHandler()
            {
                Proxy = proxy,
                UseProxy = proxyUseProxy,
                UseCookies = false
            };

            return webRequestHandler;
        }
    }




    public class PushHandler : IRequestHandler<Request_PushFromBackend, Response_PushFromBackend>
    {
        private readonly IDBCommander _commander;
        private readonly ILogger<PushHandler> _logger;

        public PushFromBackendHandler(ILogger<PushHandler> logger, IDBCommander commander)
        {
            _logger = logger;
            _commander = commander;
        }

        public async Task<Response_PushFromBackend> Handle(Request_PushFromBackend request, CancellationToken cancellationToken)
        {
            var sw = Stopwatch.StartNew();
            bool isProxyUsing = false;

            try
            {

                var resultFCMcreds = await _commander.Get_FCMcredentials(); // settings from DB
                var resultProxy = await _commander.Get_ProxySettings();     // settings from DB


                var defaultApp = FirebaseApp.DefaultInstance;

                if (defaultApp == null)
                {
                    var serviceAccountEmail = resultFCMcreds?.ServiceAccountEmail;
                    var PrivateKey = resultFCMcreds?.PrivateKey;

                    var credential = new ServiceAccountCredential(
                                   new ServiceAccountCredential.Initializer(serviceAccountEmail)
                                   {
                                       ProjectId = resultFCMcreds?.ProjectId,
                                       HttpClientFactory = new ProxyHttpClientFactory2(resultProxy?.Address, (bool)resultProxy?.UseProxy, (bool)resultProxy?.BypassOnLocal),
                                   }.FromPrivateKey(PrivateKey));


                    defaultApp = FirebaseApp.Create(new AppOptions()
                    {
                        Credential = GoogleCredential.FromServiceAccountCredential(credential),
                        HttpClientFactory = new ProxyHttpClientFactory2(resultProxy?.Address, (bool)resultProxy?.UseProxy, (bool)resultProxy?.BypassOnLocal)
                    });

                }


                FirebaseAdmin.Messaging.Aps aps_data = new Aps();

                if (request.PushMode == 1)
                {
                    aps_data.ContentAvailable = true;
                }

                var message = new Message()
                {
                    //Topic = "news",
                    Token = request.FirebaseToken,
                    Apns = new ApnsConfig()
                    {
                        Aps = aps_data
                    },
                    Data = new Dictionary<string, string>()
                    {
                        ["Changed"] = "true",
                    },
                    Notification = (request.PushMode == 1) ? null : new Notification
                    {
                        Title = $"System Notification {((request.PushMode == 1) ? " (SILENT)" : " (NORMAL)")}",
                        Body = $"Message: {request.PushMessage}"
                    }
                };
                var messaging = FirebaseMessaging.DefaultInstance;


                var result = await messaging.SendAsync(message);

                _logger.LogInformation($"result: {result}");

                return new Response_PushFromBackend()
                {
                    ....
                };
            }
            catch (Exception ex)
            {
                return new Response_PushFromBackend()
                {
                    Error = ex.Message
                };
            }

        }
    }

}

关于firebase - 如何通过代理使用 FirebaseAdmin?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62881566/

相关文章:

asp.net-web-api - 如何在ConfigureServices方法中获取IOptions或将IOptions传递到扩展方法中?

azure - 从 .NET Core 1.1.1 升级到 .NET Core 1.1.2 后,Azure 上的 ASP.NET Core 网站无法启动并出现 502.5 错误

android - FCM - 以不同用户身份登录后无法接收从同一设备发送的通知

android - 在 Android Webview 中接收推送通知

java - 如何使用 Android 对 Firestore 进行分页?

ios - 获取 Firebase 存储文件的下载 URL

android - 弹出的 React Native 应用程序无法到达 Firestore 后端

firebase - Firestore查询无法获取文档

.net - 什么是 .xproj 文件以及如何在 Visual Studio 2012 中打开此项目类型?

android - Firebase 云消息传递 : strange message delivery