【问题标题】:WebRequest with proxy and credentials带有代理和凭据的 WebRequest
【发布时间】:2012-11-26 19:29:28
【问题描述】:

我有以下情况:

要连接到互联网,我使用代理...我不确切知道代理设置,但我们使用 url 自动检索配置等...

之后,要连接到外部资源,我必须提供与我的机器凭据不同的用户凭据。

我现在的问题:

如何将 no 连接到某些资源,例如 google? 我有以下代码当然不起作用:

        string url = @"http://www.google.com";
        WebRequest request = WebRequest.Create(url);

        Console.WriteLine("Starting");

        using (WebResponse webResponse = request.GetResponse())
        {
            //TODO
        }
        Console.WriteLine("Finished");
        Console.ReadLine();

还尝试了这个额外的道具:

        request.Proxy = WebRequest.DefaultWebProxy;
        request.Credentials = CredentialCache.DefaultCredentials;
        request.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
        NetworkCredential networkCredential = new NetworkCredential("usr", "psw");
        request.Credentials = networkCredential;

知道怎么做吗?

【问题讨论】:

    标签: c# web


    【解决方案1】:

    您可以尝试添加类似于您的 App.Config 的内容:

    <system.net>
      <defaultProxy enabled="true" useDefaultCredentials="true">
      </defaultProxy>
    </system.net>
    

    如果这不起作用,您可以像这样构建自己的代理类:

    添加类似于您的 App.Config 的内容:

    <system.net>
      <defaultProxy enabled="true" useDefaultCredentials="false">
        <module type="Your.MyProxy, YourApp" />
      </defaultProxy>
    </system.net>
    

    Your.Proxy 是代理类的命名空间和类名。然后创建一个类似这样的类:

    // In namespace Your
    // ...
    
    public class MyProxy: IWebProxy
    {
        /// ====================================================================
        /// <summary>
        /// The credentials to submit to the proxy server for authentication.
        /// </summary>
        /// <returns>An <see cref="T:System.Net.ICredentials"/> instance that contains the 
        /// credentials that are needed to authenticate a request to the proxy server.</returns>
        /// ====================================================================
        public ICredentials Credentials
        {
            get 
            {
                // Read all values from the AppSettings
                string username = ConfigurationManager.AppSettings["ProxyUsername"].ToString();
                string password = ConfigurationManager.AppSettings["ProxyPassword"].ToString();
                string domain = ConfigurationManager.AppSettings["ProxyDomain"].ToString();
                return new NetworkCredential(username, password, domain); 
            }            
            set { }
        }
    
        /// ====================================================================
        /// <summary>
        /// Returns the URI of a proxy.
        /// </summary>
        /// <param name="destination">A <see cref="T:System.Uri"/> that specifies the requested 
        /// Internet resource.</param>
        /// <returns>
        /// A <see cref="T:System.Uri"/> instance that contains the URI of the proxy used to 
        /// contact <paramref name="destination"/>.
        /// </returns>
        /// ====================================================================
        public Uri GetProxy(Uri destination)
        {
            // Use the proxy server specified in AppSettings
            string proxy = ConfigurationManager.AppSettings["ProxyServer"].ToString();
            return new Uri(proxy);
        }
    
        /// ====================================================================
        /// <summary>
        /// Indicates that the proxy should not be used for the specified host.
        /// </summary>
        /// <param name="host">The <see cref="T:System.Uri"/> of the host to check for proxy use.</param>
        /// <returns>
        /// true if the proxy server should not be used for <paramref name="host"/>; otherwise, false.
        /// </returns>
        /// ====================================================================
        public bool IsBypassed(Uri host)
        {
            // Ignore localhost URIs
            string[] bypassUris = ConfigurationManager.AppSettings["ProxyBypass"].ToString().Split(',');
            foreach (string bypassUri in bypassUris)
            {
                if (host.AbsoluteUri.ToLower().Contains(bypassUri.Trim().ToLower()))
                {
                    return true;
                }
            }
    
            return false;
        }
    }
    

    然后您可以在 App.Config 中添加更多设置,例如:

    <!-- New Proxy settings -->
    <add key="ProxyUsername" value="User123" />
    <add key="ProxyPassword" value="Password456" />
    <add key="ProxyDomain" value="your.domain" />
    <add key="ProxyServer" value="http://123.456.789.000:8080" />
    <add key="ProxyBypass" value="localhost, another_server" />
    

    我希望这可以帮助您走上正轨?

    【讨论】:

    • 所以你不能只定义一些东西,你真的必须创建这个类吗?还有很多我不知道的属性,当我使用浏览器上网时,它会从设置中提供的链接设置代理。还有其他方法吗?
    • 你不一定需要这个类。最初,您应该尝试仅使用默认凭据的第一个选项。然后,我对此进行了扩展,以展示如果您需要更多控制权,您可以如何在此基础上进行构建(我们发现使用默认凭据并不总是有效)。
    猜你喜欢
    • 2011-03-13
    • 2021-12-17
    • 1970-01-01
    • 2011-03-03
    • 2015-04-15
    • 2013-08-05
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多