C# HttpWebRequest with Proxy Credentials not passing credentials to proxy server

user2186725 picture user2186725 · Mar 19, 2013 · Viewed 15.3k times · Source

I am currently following something similar to this:

 HttpWebRequest myWebRequest = (HttpWebRequest) WebRequest.Create("http://www.microsoft.com");
IWebProxy proxy = myWebRequest.Proxy;
Uri newUri = new Uri(proxyAddress);
myProxy.Address = newUri;
... (setting of username/password for proxy)
myProxy.Credentials = new NetworkCredential(username, password);
 myWebRequest.Proxy = myProxy;

HttpWebResponse myWebResponse = (HttpWebResponse) myWebRequest.GetResponse();

I'm running the code from an IIS 7.5 hosted application that needs to verify that URL's are contactable before a process continues. As the service shouldn't have access to the outside world, I need to use a specific proxy server with credentials given to me by our IT department.

Unfortunately, no matter what I try (system.net/default proxy in the app.config, with an associated module class to create the url and credentials, or something like above)), the proxy server does not get those credentials passed to it.

Is there anything I've likely missed? I've tried running this from a VS2010 web app in debug mode with the app running from IIS with the default Application Pool Identity. and the same from a server in our QA environment and nothing changes - it either doesn't use the proxy at all, or just doesn't send the credentials.

I've also tried setting PreAuthenticate = true and UseDefaultCredentials both to true AND k, and no change.

Any ideas on what I'm missing?

Answer

Bill Agee picture Bill Agee · Apr 2, 2013

Edit: Sorry, misunderstood your question at first - corrected answer below:

I would try creating a new WebProxy object, setting its credentials, and then setting it as your request's proxy (rather than obtaining the existing proxy object from the request and modifying it):

HttpWebRequest myWebRequest =
    (HttpWebRequest) WebRequest.Create("http://www.microsoft.com");
IWebProxy proxy = new WebProxy(proxyAddress);
string proxyUsername = @"foo";
string proxyPassword = @"bar";
proxy.Credentials = new NetworkCredential(proxyUsername, proxyPassword);
myWebRequest.Proxy = proxy;