【问题标题】:How to access the Internet through Proxy in C#C#中如何通过代理访问互联网
【发布时间】:2011-01-11 14:50:38
【问题描述】:

我正在使用 C# 设计一个 Windows 窗体应用程序。该应用程序在连接到 Internet 时可以顺利执行其功能,但真正的问题是当我们在我们的大学尝试该应用程序时开始。

我们的学院使用代理网关连接到网络。代理服务器为192.168.120.5,代理端口为8080。每个学生都有一个唯一的用户名和密码。

我怎样才能越过这个障碍?我正在尝试创建到目标 IP 的代理连接:

WebRequest request = WebRequest.Create("http://www.example.com");  
request.Proxy = new WebProxy("192.168.120.5", 8080); 

这对我有什么帮助吗?如果是,我在哪里输入用户名和密码凭据?

【问题讨论】:

    标签: .net proxy


    【解决方案1】:

    是的,您可以使用它...虽然使用 WebRequest.DefaultWebProxy 可能更简单

    WebProxy proxyObject = new WebProxy("http://proxyserver:80/",true);
    proxyObject.Credientials = new NetworkCredential(UserName, "bla");
    WebRequest req = WebRequest.Create("http://www.contoso.com");
    req.Proxy = proxyObject;
    

    不过作为旁注,您可以通过设置

    来使用本地默认凭据
    proxyObject.UseDefaultCredentials = true;
    

    如果您尝试使用它,您必须确保 proxyObject.Credentials = null。
    所有这一切的 msdn 站点都在这里 MSDN WebProxy

    【讨论】:

      【解决方案2】:

      这会有点晚,但这可能会对处于相同情况的其他人有所帮助,首先为您的代理配置创建一个新类,如下所示

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Net;
      using System.Web;
      
      namespace Your_name_space
      {
          public class Proxy : IWebProxy
          {
              public ICredentials Credentials
              {
                  get
                  {
                      return new NetworkCredential("username", "password", "domaine");
                  }
                  set { }
              }
      
              public Uri GetProxy(Uri destination)
              {
                  return new Uri("your_proxy_address:port");
              }
      
              public bool IsBypassed(Uri host)
              {
                  return false;
              }
          }
      }
      

      接下来将此作为模块添加到您的应用配置中的 configuration/system.net 部分。

        <system.net>
          <defaultProxy enabled="true" useDefaultCredentials="false" >
            <module type="Your_name_space.Proxy , your_assembly_name" />
          </defaultProxy>
        </system.net>
      

      如果您确实想使用默认会话凭据,请在代理类中替换 这个:

      new NetworkCredential("username", "password", "domaine");
      

      通过

      CredentialCache.DefaultCredentials;
      

      我希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 2013-09-05
        • 1970-01-01
        • 1970-01-01
        • 2016-10-17
        • 2014-11-16
        • 1970-01-01
        • 2014-10-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多