我有一个检查URL是否存在的函数
private bool UrlExists(string url){
try
{
var request = WebRequest.Create(url) as HttpWebRequest;
if (request == null) return false;
request.Method = "HEAD";
using (var response = (HttpWebResponse)request.GetResponse())
{
return response.StatusCode == HttpStatusCode.OK;
}
}
catch (UriFormatException uriException)
{
//Invalid Url
Log.Error(this, uriException.Message);
return false;
}
catch (WebException webException)
{
//Unable to access url
Log.Error(this, webException.Message);
return false;
}
catch (Exception ex) {
Log.Error(this, ex.Message);
return false;
}}
但它并没有像我期望的那样发挥作用。
一些URL工作,例如stackoverflow,一些本地URL,...
但是对于我已经部署到临时站点的特殊站点,我可以打开它,但该方法会将异常视为The remote server returned an error: (500) Internal Server Error.
我的方法有什么问题?什么是测试URL的最佳解决方案?
p.s:我还尝试使用另一种检查URL可访问的方法,但它也不适用于该URL
private async Task<bool> UrlIsReachable(string url){
try
{
using (var client = new HttpClient())
{
//var response = await client.GetAsync(url);
var httpRequestMsg = new HttpRequestMessage(HttpMethod.Head, url);
var response = await client.SendAsync(httpRequestMsg);
return (response.StatusCode == HttpStatusCode.OK || response.IsSuccessStatusCode);
}
}
catch (Exception ex)
{
Log.Error(this, ex.Message);
return false;
}}
提前致谢。