【问题标题】:Can I extend all HttpWebRequest instances in my project?我可以在我的项目中扩展所有 HttpWebRequest 实例吗?
【发布时间】:2013-12-06 11:27:24
【问题描述】:

我在我的项目中多次使用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 并添加此代码(作为函数)。

有没有快速的方法?

【问题讨论】:

  • WebRequest.DefaultWebProxy?
  • ?我正在使用HttpWebRequest....
  • 但是你说你使用WebRequest.Create(requestedData)创建那些HttpWebRequest对象,而WebRequest有一个名为DefaultWebProxy的静态属性。
  • 是的,但是如果是这样,我需要用所有代码替换所有连接!我刚刚问过我是否可以以某种方式扩展它...
  • 你似乎试图为自己做比你需要的更多的工作。我是说您创建了代理对象的一个​​实例,将其分配给WebRequest.DefaultWebProxy,之后,对WebRequest.Create() 的每次调用都已经分配了该代理。无需为创建的每个实例单独运行代码。

标签: c# .net httprequest


【解决方案1】:

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

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属性已经设置正确了。

【讨论】:

    【解决方案2】:

    您还可以在配置中使用<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.

    【讨论】:

      猜你喜欢
      • 2019-03-16
      • 1970-01-01
      • 2013-05-31
      • 1970-01-01
      • 2012-11-07
      • 1970-01-01
      • 2023-03-28
      • 2014-10-06
      • 2012-10-24
      相关资源
      最近更新 更多