C# 通过代理连接 [英] C# Connecting Through Proxy

查看:21
本文介绍了C# 通过代理连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在办公室工作,需要通过特定的 http 代理建立所有连接.我需要编写一个简单的应用程序来从网络服务器查询一些值 - 如果没有代理,这很容易.如何使 C# 应用程序能够识别代理?如何通过代理建立任何类型的连接?

I work in a office which requires all connections to be made through a specific http proxy. I need to write a simple application to query some values from a webserver - it's easy if there were no proxy. How can I make the C# application proxy-aware? How can I make any sort of connection through a proxy?

推荐答案

这可以通过编程方式、在您的代码中或在 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.

这篇关于C# 通过代理连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆