C# 如何从WebRequest中删除代理并保持DefaultWebProxy不变
我使用FtpWebRequest做一些FTP工作,我需要直接连接(没有代理)。但是WebRequest.DefaultWebProxy包含IE代理设置(我估计) 我的代码是大型应用程序中的一部分,我不想更改C# 如何从WebRequest中删除代理并保持DefaultWebProxy不变,c#,.net,C#,.net,我使用FtpWebRequest做一些FTP工作,我需要直接连接(没有代理)。但是WebRequest.DefaultWebProxy包含IE代理设置(我估计) 我的代码是大型应用程序中的一部分,我不想更改WebRequest.DefaultWebProxy,因为它是全局静态属性,可能会对应用程序的其他部分产生不利影响 知道怎么做吗?尝试将代理设置为空的WebProxy,即: request.Proxy = new WebProxy(); 这将创建一个空代理。实际上,将其设置为null也足以禁
WebRequest.DefaultWebProxy
,因为它是全局静态属性,可能会对应用程序的其他部分产生不利影响
知道怎么做吗?尝试将代理设置为空的WebProxy,即:
request.Proxy = new WebProxy();
这将创建一个空代理。实际上,将其设置为null也足以禁用自动代理检测,您可能会节省一些周期:) 将此项添加到配置中:
<system.net>
<defaultProxy enabled="false" useDefaultCredentials="false">
<proxy />
<bypasslist />
<module />
</defaultProxy>
</system.net>
没问题,这件事刚才还难住了我。值得注意的是,上面说要使用GlobalProxySelection.GetEmptyWebProxy()
来获取一个空代理。但是如果您尝试此操作,Visual Studio将通知您GlobalProxySelection
类已过时,您应该使用WebRequest.DefaultWebProxy
。。。这正是OP不想要的。事实上,如果我没有记错的话(如代码段注释中所述),设置为null没有帮助。禁用自动代理检测将影响应用程序的其余部分,我也无法做到这一点。无论如何谢谢你
request.Proxy = null;
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();
}
<system.net>
<defaultProxy enabled="false" useDefaultCredentials="false">
<proxy />
<bypasslist />
<module />
</defaultProxy>
</system.net>