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?
You'll have to handle the exception, but you can use pattern matching and the
Statusproperty onWebException(which contains a WebExceptionStatus) to control your interpretation of the response more easily: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.