c# - IE浏览器关闭时C#HttpWebRequest报“407 Proxy Authentication Required”错误
问题描述
背景
目前,我们有一个代理设置通过 wpad 文件分发的场景。网络中的每台机器都应在 Internet Explorer 上设置以下配置:
在 IE 上配置此代理设置后,我可以毫无问题地通过 HTTP 导航。在 IE 中打开网页之前,我从未被要求提供任何用户名/密码凭据以通过代理。
问题
在这里,我们有一个应用程序,它运行以下 C# 代码来进行数据的流式下载:
public Stream PostStream(string api, string data)
{
var payload = Encoding.UTF8.GetBytes(data);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(new Uri(api));
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json; charset=UTF-8";
httpWebRequest.ContentLength = payload.Length;
httpWebRequest.AllowReadStreamBuffering = false;
httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
httpWebRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;
httpWebRequest.UseDefaultCredentials = true;
using (var stream = httpWebRequest.GetRequestStream())
{
stream.Write(payload, 0, payload.Length);
}
var httpWebResponse = httpWebRequest.GetResponse();
return httpWebResponse.GetResponseStream();
}
AFAIK,httpWebRequest
应该能够自动创建一个默认Proxy
实例,它继承了 IE 上的代理设置,(我调试了代码,我可以看到自动配置脚本已在代理实例中加载/使用),有趣的是:
- 如果我在计算机上保持 Internet Explorer 打开,然后运行我的应用程序,一切正常
- 但是如果我关闭 Internet Explorer 然后运行我的应用程序,它会抛出“需要 407 代理身份验证”异常
所以,我的问题是:
- 当我使用我的应用程序下载数据时,保持 Internet Explorer 处于打开状态的原因是什么?
- 如何改进我的 C# 代码来解决此问题?也许我可以在代码中设置代理凭据,但是凭据是什么?当我访问 HTTP 资源时,从来没有要求我提供任何凭据
提前致谢!
解决方案
推荐阅读
- html - 我的 figma 网页设计不适合实际页面,它向右无穷大
- c - 如何处理C中的特殊字符?
- python - 除非重新启动服务器,否则 Django 查询集不会在实时服务器上更新,而是在本地更新
- java - Mapreduce 中的键是按值传递还是按引用传递?
- spring - 使用百里香叶获取POST控制器弹簧中的参数
- javascript - discord.js 音乐机器人 dispatcher.on("finish") 逻辑运行多次从队列中删除歌曲然后断开机器人
- c++ - 转换模板类实例后的虚函数问题
- reactjs - TypeScript 和 styled-components:没有重载匹配这个调用
- ruby-on-rails - 使用 docker 和 docker-compose 运行 RSpec 规范
- python - 如何将我的输出从行转换为列?