【问题标题】:How to remove proxy from WebRequest and leave DefaultWebProxy untouched如何从 WebRequest 中删除代理并保持 DefaultWebProxy 不变
【发布时间】:2019-05-20 23:31:17
【问题描述】:

我使用 FtpWebRequest 做一些 FTP 的事情,我需要直接连接(没有代理)。但是 WebRequest.DefaultWebProxy 包含 IE 代理设置(我认为)。

WebRequest request = WebRequest.Create("ftp://someftpserver/");
// request.Proxy is null here so setting it to null does not have any effect
WebResponse response = request.GetResponse();
// connects using WebRequest.DefaultWebProxy

我的代码是大型应用程序中的一部分,我不想更改WebRequest.DefaultWebProxy,因为它是全局静态属性,它可能会对应用程序的其他部分产生不利影响。

知道怎么做吗?

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    尝试将代理设置为空的WebProxy,即:

    request.Proxy = new WebProxy();
    

    这应该会创建一个空代理。

    【讨论】:

    • 没有问题,这个问题前一阵难倒我。
    • 值得注意的是,MSDN documentation 表示使用GlobalProxySelection.GetEmptyWebProxy() 来获取空代理。但是,如果您尝试此 Visual Studio 会通知您 GlobalProxySelection 类已过时,您应该改用 WebRequest.DefaultWebProxy ...这正是 OP 想要的。
    【解决方案2】:

    实际上将其设置为 null 也足以禁用自动代理检测,您可能会节省一些周期:)

    request.Proxy = null;
    

    http://msdn.microsoft.com/en-us/library/fze2ytx2.aspx

    【讨论】:

    • 实际上,如果我没记错的话,设置为 null 并没有帮助(如 sn-p 评论中所述)。禁用自动代理检测会影响应用程序的其余部分,我也不能这样做。还是谢谢
    【解决方案3】:
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(yourRequestUrl);
            if (webRequest.Proxy != null)
            {
                webRequest.Proxy = null;
            }
    
            webRequest.KeepAlive = true;
            webRequest.Method = "POST";
            webRequest.ContentType = "application/json";
            var json = JsonConvert.SerializeObject(yourObject);
            ASCIIEncoding encoder = new ASCIIEncoding();
            byte[] postBytes = encoder.GetBytes(json);
            webRequest.ContentLength = postBytes.Length;
            webRequest.CookieContainer = new CookieContainer();
            String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(string.Format("{0}:{1}", userName, password)));
            webRequest.Headers.Add("Authorization", "Basic " + encoded);
            Stream requestStream = webRequest.GetRequestStream();
            requestStream.Write(postBytes, 0, postBytes.Length);
            requestStream.Close();
    
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
            string result;
            using (StreamReader rdr = new StreamReader(response.GetResponseStream()))
            {
                    result = rdr.ReadToEnd();
    }
    

    【讨论】:

      【解决方案4】:

      将此添加到配置中:

      <system.net>
        <defaultProxy enabled="false" useDefaultCredentials="false">
          <proxy />
          <bypasslist />
          <module />
        </defaultProxy>
      </system.net>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多