views:

182

answers:

3

In a .NET application I am writing, I need to detect whether a particular URL is available. For the average user with a default DNS server, an invalid address would end up throwing a WebException. However, at home I am using OpenDNS. When I request an invalid address at home, the automatic OpenDNS redirect makes .NET believe the request succeeded. How can I detect when the DNS server is not giving me the address I requested?

Here's some of the code:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://...");
request.AllowAutoRedirect = false;

try
{
    WebResponse response = request.GetResponse();

    using (Stream stream = response.GetResponseStream())
    {
        // Do work
        ...
    }
}
catch (WebException ex)
{
    // Handle normal errors
    ...
}
+1  A: 

Check to see if the WebResponse.ResponseUri value matches the original URL requested. http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.responseuri.aspx

John Sheehan
I tried that, but unfortunately they match.
Zach Johnson
In which cases does ResponseUri not match the original URL if `AllowAutoRedirect = false`?
dtb
Since OpenDNS simulates a successful request I doubt you'll be able to tell without looking for it specifically like David mentions.
John Sheehan
@dtb. I just realized that the ResponseUri is different from the requested url when I set `AllowAutoRedirect` to `true`.
Zach Johnson
+2  A: 

Have you tried looking at the HTTP status code that is returned?

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

if (response.StatusCode == HttpStatusCode.OK)
{
    using (Stream stream = response.GetResponseStream())
    {
        // Do work
        ...
    }
}
else
{
    // Error
}
dtb
This works when `AllowAutoRedirect = false`.
Zach Johnson
A: 

If the ResponseUri matches the original URL, then the best you can do is look at the response text and see if it "looks" like the OpenDNS page.

David