且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C# 通过代理连接

更新时间:2022-10-31 15:06:20

这可以通过编程方式、在您的代码中或在 web.config 或 app.config 中以声明方式轻松实现.

This is easily achieved either programmatically, in your code, or declaratively in either the web.config or the app.config.

您可以像这样以编程方式创建代理:

You can programmatically create a proxy like so:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("[ultimate destination of your request]");
WebProxy myproxy = new WebProxy("[your proxy address]", [your proxy port number]);
myproxy.BypassProxyOnLocal = false;
request.Proxy = myproxy;
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse) request.GetResponse();

您基本上是将 WebProxy 对象分配给 request 对象的 proxy 属性.此 request 然后将使用您定义的 proxy.

You're basically assigning the WebProxy object to the request object's proxy property. This request will then use the proxy you define.

要以声明方式实现相同的目的,您可以执行以下操作:

To achieve the same thing declaratively, you can do the following:

<system.net>
  <defaultProxy>
    <proxy
      proxyaddress="http://[your proxy address and port number]"
      bypassonlocal="false"
    />
  </defaultProxy>
</system.net>

在您的 web.config 或 app.config 中.这将设置所有 http 请求都将使用的默认代理.根据您需要实现的具体目标,您可能需要也可能不需要 defaultProxy/proxy 元素,所以请参考到那些文档.

within your web.config or app.config. This sets a default proxy that all http requests will use. Depending upon exactly what you need to achieve, you may or may not require some of the additional attributes of the defaultProxy / proxy element, so please refer to the documentation for those.