简体   繁体   English

以编程方式设置默认代理而不是使用app.config

[英]set default proxy programmatically instead of using app.config

Being behind a proxy, my .Net 4.0 C# application only works when there is an app.config with the following content: 作为代理的后面,我的.Net 4.0 C#应用程序仅在存在具有以下内容的app.config时才有效:

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

Now since I don't want to have an app.config and since embedding app.config is not recommended, what is the C# code that has the same effect as that xml chunk in the app.config and where do I place it? 既然我不想拥有app.config并且因为不建议嵌入app.config,那么与app.config中的xml chunk具有相同效果的C#代码是什么?我在哪里放置它?

You can use WebRequest.DefaultWebProxy or GlobalProxySelection.Select 您可以使用WebRequest.DefaultWebProxyGlobalProxySelection.Select

System.Net.GlobalProxySelection.Select = new WebProxy(ip,port);

OR 要么

System.Net.WebRequest.DefaultWebProxy = new WebProxy(ip,port);

The following code worked for me: 以下代码对我有用:

System.Net.WebRequest.DefaultWebProxy.Credentials 
    = System.Net.CredentialCache.DefaultNetworkCredentials;

you can use WebProxy from System.Net 您可以使用System.Net WebProxy

WebProxy proxyObject = new WebProxy("PROXYIP",PORTNO);
WebRequest req = WebRequest.Create("http://www.stackoverflow.com");
req.Proxy = proxyObject;

More details at MSDN MSDN上的更多细节

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM