我可以在项目中扩展所有HttpWebRequest实例吗?

时间:2013-12-06 11:27:25

标签: c# .net httprequest

我在我的项目中多次使用HttpWebRequest

HttpWebRequest request = WebRequest.Create(requestedData) as HttpWebRequest;

现在,服务器的管理员为我的连接设置代理。我想在任何情况下添加这样的代码:

IWebProxy proxy = new WebProxy(Proxy, ProxyPort);
NetworkCredential nc = new NetworkCredential();

nc.UserName = ProxyLogin;
nc.Password = ProxyPassword;
request.Proxy = proxy;
request.Proxy.Credentials = nc;

在我的项目中没有搜索request并添加此代码(作为函数)。

有快节奏吗?

2 个答案:

答案 0 :(得分:3)

在启动期间(例如,在控制台项目的Main开始时,在Global.asax的Application_Start内为Web项目,运行以下代码:

IWebProxy proxy = new WebProxy(Proxy, ProxyPort);
NetworkCredential nc = new NetworkCredential();

nc.UserName = ProxyLogin;
nc.Password = ProxyPassword;
proxy.Credentials = nc;
WebRequest.DefaultWebProxy = proxy;

在上面的代码运行之后,任何代码如下所示:

HttpWebRequest request = WebRequest.Create(requestedData) as HttpWebRequest;

会发现Proxy属性已正确设置。

答案 1 :(得分:1)

您还可以使用<defaultProxy> element在配置中为应用程序的所有HTTP请求设置代理:

<configuration>
  <system.net>
    <defaultProxy>
      <proxy
        usesystemdefaults="true"
        proxyaddress="http://192.168.1.10:3128"
        bypassonlocal="true"
      />
      <bypasslist
        <add address="[a-z]+\.contoso\.com" />
      </bypasslist>
    </defaultProxy>
  </system.net>
</configuration>

虽然doesn't seem to work with authentication