如何在Firebase GetAccessToken中设置代理?

时间:2018-03-13 16:13:59

标签: firebase proxy firebase-notifications

我需要在我的c#程序中设置代理服务器和端口,同时在我的令牌请求中使用Google API(推送通知服务)。 或者说我认为我需要它,因为在这种方法中

private static async Task<string> GetAccessToken()
    {
        string retVal = string.Empty;

        try
        {
            string sPathFile = ConfigurationManager.AppSettings["FCMkeyFullPath"];
            using (var stream = new FileStream(sPathFile, FileMode.Open, FileAccess.Read))
            {                
                var credential = GoogleCredential.FromStream(stream).CreateScoped("https://www.googleapis.com/auth/firebase.messaging");                
                retVal = await credential.UnderlyingCredential.GetAccessTokenForRequestAsync().ConfigureAwait(false);   // <-- EXCEPTION HERE             
            }
        }
        catch(Exception ex)
        {
            retVal = ex.Message;
        }

        return retVal;
    }

我得到了这个例外:

  

发送请求时发生错误。

网上冲浪我发现了课程

public class ProxySupportedHttpClientFactory : HttpClientFactory
{
    protected override HttpMessageHandler CreateHandler(CreateHttpClientArgs args)
    {
        //ICredentials credentials = new NetworkCredential("user1", "user1");
        //var proxy = new WebProxy("http://127.0.0.1:3128", true, null, credentials);
        var proxy = new WebProxy("http://127.0.0.1:3128", true, null, null);        
        var webRequestHandler = new HttpClientHandler()
        {
            UseProxy = true,
            Proxy = proxy,
            UseCookies = false
        };
        return webRequestHandler;
    }
}

但我不知道如何使用它......

1 个答案:

答案 0 :(得分:0)

解决了! 我在C#web应用程序解决方案中添加了一个 MyProxyAssembly 项目,其中只有一个类如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace MyProxyAssembly.dll
{
    public class MyProxy : IWebProxy
    {
        public ICredentials Credentials
        {
            get { return new NetworkCredential("user", "password"); }
            //or get { return new NetworkCredential("user", "password","domain"); }
            set { }
        }

        public Uri GetProxy(Uri destination)
        {            
            return new Uri("http://myproxy:8080");
        }

        public bool IsBypassed(Uri host)
        {
            return false;
        }
    }
}

这个项目的输出是一个DLL库,我将它包含在我的解决方案依赖项和Web项目引用中。然后我在web.config中添加了这些行:

<system.net>
    <defaultProxy enabled="true" useDefaultCredentials="false">
      <module type = "MyProxyAssembly.dll.MyProxy, MyProxyAssembly" />
    </defaultProxy>
  </system.net>

通过这种方式,我将我的Web应用程序设置为使用代码中编写的代理凭据。它运作正常。