0

I'm using http://dictionary.reference.com/browse/:word and check the status of returned response to evaluate whether the 'word' definition exists or not. It works fine for correct words (200 status code). But for those spelled incorrectly (404 status code), I'm unable to catch the status code from HttpWebRequest.GetResponse(), as it returns null?

The thing is I'm using PostMan to check and I did receive status code 404 there for the following url:

http://dictionary.reference.com/browse/sdfsdsdc

Here's my implementation:

string baseURL = "http://dictionary.reference.com/browse";
bool result = false;
try
{                
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseURL + "/" + word);
    request.Method = "GET";
    //request.Timeout = 2000;
    request.KeepAlive = false;
    request.ContentType = "text/html; charset=UTF-8";
    Console.WriteLine(request.RequestUri);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    HttpStatusCode statusCode = response.StatusCode;
    int statusCodeNumber = (int)statusCode;

    Console.WriteLine("Status Code: " + statusCode + " - status number: " + statusCodeNumber);
    try
    {
        if (statusCodeNumber == 200) result = true;
        else if (statusCodeNumber == 404) { result = false; }
        else { throw new UnknownStatusCodeException(); }
    }
    catch (UnknownStatusCodeException e) {}
    response.Close();                
    }
    catch (WebException e) {
    }
}

Here's the WebException I caught

alt tag

full-size-pic

Could someone give me some pointers? Thanks

rustyengineer
  • 343
  • 3
  • 16
  • you can handle your error from `web.config` file, did you try this ? – Sunil Kumar Aug 23 '16 at 05:12
  • @SunilKumar technically I'm not using MVC at all, as this is simply a C# project with a main() method using console to input/output. One requirement of the assignment is to generate and call the url to detect if spelling of given word is correct or not. Is there any other way I can work around this? – rustyengineer Aug 23 '16 at 05:23
  • refer this link :http://stackoverflow.com/questions/1949610/how-can-i-catch-a-404 – Sunil Kumar Aug 23 '16 at 05:28
  • @SunilKumar I already tried that. The problem was e.Response gave me null. If you check my image, you'll see that. – rustyengineer Aug 23 '16 at 05:37

0 Answers0