Alnedru
Alnedru

Reputation: 2655

WebRequest with proxy and credentials

I have the following situation:

To connect to the internet I use proxy ... I don't know exactly the proxy settings, but we use the url to retrieve the configuration automatically etc ...

After that to connecto to the ouside resources I have to provide the user credentials which are not the same as my machine credentials.

My question now:

How do I connect no to some resource for example to google? I have following code which ofcourse doesn't work:

        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();

Also tried with this extra props:

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

Any idea how to do it?

Upvotes: 0

Views: 2080

Answers (1)

Belogix
Belogix

Reputation: 8147

You could try adding something similar to your App.Config:

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

If that doesn't work you could build your own proxy class like this:

Adding something similar to your App.Config:

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

Where Your.Proxy is the namespace and class name of your proxy class. Then create a class similar to this:

// 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;
    }
}

Then you can just add some more settings to your App.Config like:

<!-- 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" />

I hope that can help get you on the right track?

Upvotes: 1

Related Questions