How to handle "405 error, Method Not Allowed." without an exception

759 views Asked by At

Right now I am solving an issue that I made a HttpWebRequest to server and checking if the server answers. Any answer which means that the server was reached is positive for me. So if I will get an answer:

  • HttpStatusCode.OK (it's ok for me)
  • 405 Method not allowed (it's ok for me).

Code:

try
{
    var myHttpWebRequest = (HttpWebRequest)WebRequest.Create(_endPointUri);
    myHttpWebRequest.Timeout = _timeoutMs;

    var myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

    if (myHttpWebResponse.StatusCode == HttpStatusCode.OK)
        return true;
}
catch (WebException e)
{
    return e.Message.Contains("The remote server returned an error: (405) Method Not Allowed.");
}
catch (Exception e)
{
}
return false;

How to handle this situation without any exception?

1

There are 1 answers

0
jamarchist On BEST ANSWER

You'll have to handle the exception, but you can use pattern matching and the Status property on WebException (which contains a WebExceptionStatus) to control your interpretation of the response more easily:

var request = HttpWebRequest.Create(uri);
request.Timeout = timeout;

try
{
    var response = (HttpWebResponse) request.GetResponse();
    return true;
}
catch (WebException connectionError) when (
    connectionError.Status == WebExceptionStatus.NameResolutionFailure ||
    connectionError.Status == WebExceptionStatus.Timeout)
{
    return false;
}
catch
{
    return true;
}

Here is a dotnetfiddle that uses the above code to determine whether or not an endpoint 'exists' in 4 different scenarios: (1) the uri is accessible and returns an 'OK' status code, (2) the uri can't be resolved, (3) the uri 'exists' but times out, and (4) the uri exists and returns a 405.

You can edit the conditional patterns in the exception handling to fill out your requirements for additional scenarios.