.net core 2.0代理请求始终生成http 407(需要代理身份验证)

时间:2017-12-18 18:15:46

标签: http asp.net-core .net-core webproxy

我试图通过.net core 2.0 Web应用程序中的WebProxy发出HTTP请求。我在.net框架中得到的代码工作正常,所以我知道(相信)它不是一个环境问题。我也尝试使用HttpWebRequestHttpClient来发出请求,但这两种机制总是导致.net核心中的407(需要代理身份验证)http错误。就像在.net核心中一样,我提供的凭证总是被忽略。

以下是我一直在使用的代码:

public void Test() 
{
    var cred = new NetworkCredential("xxxxx", "yyyyyy");
    var proxyURI = new Uri("http://xxx.xxx.xxx.xxx:80");
    var destinationURI = new Uri("http://www.bbc.co.uk");
    WebProxy proxy = new WebProxy(proxyURI, false) { UseDefaultCredentials = false, Credentials = cred };

    MakeProxyRequestViaHttpWebRequest(proxy, destinationURI);
    MakeProxyRequestViaHttpClient(proxy, destinationURI);
}

private void MakeProxyRequestViaHttpClient(WebProxy proxy, Uri destination)
{
    HttpClientHandler handler = new HttpClientHandler()
    {
        Proxy = proxy,
        UseProxy = true,
        PreAuthenticate = true,
        UseDefaultCredentials = false
    };

    HttpClient client = new HttpClient(handler);
    HttpResponseMessage response = client.GetAsync(destination).Result;
    if (response.IsSuccessStatusCode)
    {
        HttpContent content = response.Content;
        string htmlData = content.ReadAsStringAsync().Result;
    }
    else
    {
        HttpStatusCode code = response.StatusCode;
    }
}

private void MakeProxyRequestViaHttpWebRequest(WebProxy proxy, Uri destination)
{
    HttpWebRequest req = HttpWebRequest.Create(destination) as HttpWebRequest;
    req.UseDefaultCredentials = false;
    req.Proxy = proxy;
    req.PreAuthenticate = true;

    using (WebResponse response = req.GetResponse())
    {
        using (StreamReader responseStream = new StreamReader(response.GetResponseStream()))
        {
            string htmlData = responseStream.ReadToEnd();
        }
    }
}

我在.net核心中尝试了以下内容,但结果总是407:

  1. 在控制台应用中运行代码
  2. 实施IWebProxy并将其用作代理
  3. 在WebProxy,HttpClient等上设置其他属性的默认值(在上面的示例中删除,因为它在.net标准下工作正常)
  4. 我已经没有想法和尝试了。我有以下问题:

    1. .net core与.net framework
    2. 之间的代码是否需要不同
    3. 还有其他需要进入appsettings.json的东西(即可能进入web.config的配置)
    4. Startup.cs中是否需要任何其他配置代码
    5. 我是否应该使用外部库
    6. 如何解决问题是什么? Fiddler似乎并没有帮助,但后来我似乎并没有努力配置它。

0 个答案:

没有答案