我正在尝试通过 .net core 2.0 Web 应用程序中的 WebProxy 发出 HTTP 请求。我得到的代码在.net框架中运行良好,所以我知道(相信)这不是环境问题。我也尝试使用两者来发出请求HttpWebRequest
and HttpClient
但这两种机制总是会导致 .net core 中出现 407(需要代理身份验证)http 错误。就好像在 .net core 中我提供的凭据总是被忽略。
这是我一直在使用的代码:
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 core 中尝试了以下操作,但结果始终是 407:
- 在控制台应用程序中运行代码
- 实现 IWebProxy 并将其用作代理
- 为 WebProxy、HttpClient 等其他属性设置默认值(在上面的示例中删除,因为它在 .net 标准上运行良好)
我已经没有想法和事情可以尝试了。我有以下问题:
- .net core 与 .net Framework 之间的代码是否需要不同
- 是否还有其他内容需要进入 appsettings.json(即本应进入 web.config 的配置)
- Startup.cs中是否需要额外的配置代码
- 我应该使用外部库吗
- 我该如何解决问题所在? Fiddler 似乎没有帮助,但我并没有努力配置它。
None
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)