首页 > 解决方案 > 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 上的代理设置,(我调试了代码,我可以看到自动配置脚本已在代理实例中加载/使用),有趣的是:

所以,我的问题是:

  1. 当我使用我的应用程序下载数据时,保持 Internet Explorer 处于打开状态的原因是什么?
  2. 如何改进我的 C# 代码来解决此问题?也许我可以在代码中设置代理凭据,但是凭据是什么?当我访问 HTTP 资源时,从来没有要求我提供任何凭据

提前致谢!

标签: c#proxyhttpwebrequestcredentials

解决方案


推荐阅读