ASP..NET:检查url是否可访问或存在

时间:2017-05-05 09:04:14

标签: asp.net

我有一个检查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;
}}

提前致谢。

0 个答案:

没有答案