Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect HTTP Proxy error for WebRequest

How to detect that a WebRequest failed due to a web proxy error and not a target web server error?

try
{
    var request = (HttpWebRequest)WebRequest.Create("http://www.example.com");
    request.Proxy = new WebProxy("localhost");
    var response = request.GetResponse();

    return response.GetResponseStream();
}
catch(WebException webex)
{
    //Detect proxy failure
}
like image 973
AlexMinza Avatar asked Oct 15 '22 13:10

AlexMinza


2 Answers

It is difficult. Here are some suggestions:

  • The webex.Response.ResponseUri property contains the URI of your proxy server instead of the server you were trying to contact.
  • The webex.Response.StatusCode property is one that always refers to a proxy problem, e.g. ProxyAuthenticationRequired. Unfortunately most statuses could refer to either a proxy error or a server error.
  • The webex.Response.Headers collection contains non-standard entries that you recognise as being generated by your proxy server. For example, the Squid proxy returns the header "X-Squid-Error", with its own proprietary set of statuses.
  • The webex.Response.ResponseStream stream contains an HTML or plain text error message in a format that you recognise as being generated by your proxy server. You might test to see if it contains the URI of your proxy server.

In your catch block, make sure that you log full details of the WebException object, including all the properties mentioned above. You can then analyse the log data and develop an accurate test for proxy errors.

like image 78
Christian Hayter Avatar answered Oct 20 '22 17:10

Christian Hayter


I think you could catch InvalidOperationException and then check the message for "proxy".

The message would say:

The proxy name could not be resolved: 'localhost'

like image 41
David Kiff Avatar answered Oct 20 '22 18:10

David Kiff