如何将FirebaseAdmin与代理一起使用?

如何将FirebaseAdmin与代理一起使用?,firebase,.net-core,firebase-cloud-messaging,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;

下面的代码在本地运行得非常好。 当我通过本地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)
            {..... }

        }
    }

}
使用系统;
使用MediatR;
使用System.IO;
使用FirebaseAdmin;
使用系统线程;
使用System.Threading.Tasks;
使用FirebaseAdmin.Messaging;
使用Google.api.Auth.OAuth2;
名称空间JMGlobal.Handlers
{
公共类PushHandler:IRequestHandler
{
公共异步任务句柄(请求\推送请求,取消令牌取消令牌)
{
尝试
{
var defaultApp=FirebaseApp.DefaultInstance;
if(defaultApp==null)
{
var keyPath=Path.Combine(AppDomain.CurrentDomain.BaseDirectory,“jKey.json”);
defaultApp=FirebaseApp.Create(新建AppOptions()
{
Credential=GoogleCredential.FromFile(keyPath),
//HttpClientFactory----????
});
}
var message=新消息()
{
Token=request.FirebaseToken,
Apns=新的ApnsConfig()
{
Aps=新建FirebaseAdmin.Messaging.Aps()
{
警报=新的ApsAlert()
{
Title=“推送”,
Body=request.PushMessage
}
}
},
通知=新通知
{
Title=“系统通知”,
正文=$“消息:{request.PushMessage}”
}
};
var messaging=firebasemsaging.DefaultInstance;
var result=wait messaging.sendaync(message);//此处引发错误:“无法建立连接:无法访问网络”
返回新的响应\u Push()
{ .... };
}
捕获(例外情况除外)
{..... }
}
}
}
工作版本如下

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

        }
    }

}
使用系统;
使用MediatR;
使用System.IO;
使用FirebaseAdmin;
使用系统线程;
使用系统诊断;
使用System.Threading.Tasks;
使用FirebaseAdmin.Messaging;
使用Google.api.Auth.OAuth2;
使用System.Collections.Generic;
使用Microsoft.Extensions.Logging;
使用Newtonsoft.Json;
使用Google.api.Http;
使用System.Net.Http;
Net系统;
使用Microsoft.Extensions.Options;
名称空间JMGlobal.Handlers
{
公共类ProxyHttpClientFactory2:Google.api.Http.HttpClientFactory
{
私有只读字符串代理地址;
私有只读bool proxyUseProxy;
私有只读bool proxyBypassOnLocal;
公共ProxyHttpClientFactory2(字符串proxyAddress、bool proxyUseProxy、bool proxyBypassOnLocal)
{
this.proxyAddress=proxyAddress;
this.proxyUseProxy=proxyUseProxy;
this.proxyBypassOnLocal=proxyBypassOnLocal;
}
受保护的重写HttpMessageHandler CreateHandler(CreateHttpClientArgs args)
{
var proxy=新的WebProxy(地址:proxyAddress,BypassOnLocal:proxyBypassOnLocal,BypassList:null,凭据:null);
var webRequestHandler=newhttpclienthandler()
{
Proxy=代理,
UseProxy=proxyUseProxy,
UseCookies=false
};
返回webRequestHandler;
}
}
公共类PushHandler:IRequestHandler
{
私人只读IDBcommanderu commander;
专用只读ILogger\u记录器;
公共PushFromBackendHandler(ILogger记录器、IDB指挥官)
{
_记录器=记录器;
_指挥官=指挥官;
}
公共异步任务句柄(请求\u PushFromBackend请求,CancellationToken CancellationToken)
{
var sw=Stopwatch.StartNew();
bool isProxyUsing=假;
尝试
{
var resultfcmccreds=await _commander.Get _FCMcredentials();//来自DB的设置
var resultProxy=await _commander.Get _ProxySettings();//数据库中的设置
var defaultApp=FirebaseApp.DefaultInstance;
if(defaultApp==null)
{
var serviceAccountEmail=resultfcmccreds?.serviceAccountEmail;
var PrivateKey=resultFCMcreds?.PrivateKey;
var-credential=新的ServiceAccountCredential(
新ServiceAccountCredential.初始值设定项(serviceAccountEmail)
{
ProjectId=ResultFCCreds?ProjectId,
HttpClientFactory=new ProxyHttpClientFactory2(resultProxy?.Address,(bool)resultProxy?.UseProxy,(bool)resultProxy?.BypassOnLocal),
}.来自PrivateKey(PrivateKey));
defaultApp=FirebaseApp.Create(新建AppOptions()
{
凭证=谷歌凭证。来自ServiceAccountCredential(凭证),
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=新消息()
{