我想驗證一個url,不管它是否存在或拋出頁面未找到錯誤。任何人都可以幫助我如何在asp.net中做到這一點。 ,例如,我的網址可能類似http://www.stackoverflow.com
或www.google.com
,即它可能包含http://
或者可能不包含。當我檢查,它應該返回網頁有效,如果存在或頁面不存在,如果不存在檢查URL存在或在asp.net中拋出頁面未找到消息
我試圖HttpWebRequest
方法,但它需要在網址「http://
」。
在此先感謝。
我想驗證一個url,不管它是否存在或拋出頁面未找到錯誤。任何人都可以幫助我如何在asp.net中做到這一點。 ,例如,我的網址可能類似http://www.stackoverflow.com
或www.google.com
,即它可能包含http://
或者可能不包含。當我檢查,它應該返回網頁有效,如果存在或頁面不存在,如果不存在檢查URL存在或在asp.net中拋出頁面未找到消息
我試圖HttpWebRequest
方法,但它需要在網址「http://
」。
在此先感謝。
protected bool CheckUrlExists(string url)
{
// If the url does not contain Http. Add it.
if (!url.Contains("http://"))
{
url = "http://" + url;
}
try
{
var request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "HEAD";
using (var response = (HttpWebResponse)request.GetResponse())
{
return response.StatusCode == HttpStatusCode.OK;
}
}
catch
{
return false;
}
}
試試這個
using System.Net;
////// Checks the file exists or not.
bool FileExists(string url)
{
try
{
//Creating the HttpWebRequest
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
//Setting the Request method HEAD, you can also use GET too.
request.Method = "HEAD";
//Getting the Web Response.
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//Returns TURE if it Exist
return (response.StatusCode == HttpStatusCode.OK);
}
catch
{
//Any exception will returns false. So the URL is Not Exist
return false;
}
}
希望我幫助
您好..感謝烏拉圭回合的答覆..我檢查了它,當我通過一個URL沒有的 「http://」,如「WWW .google.com「會引發此錯誤」無效的URI:URI的格式無法確定。「我想處理這類問題。 – Hulk 2012-07-26 14:04:14
感謝您的答覆..你的想法很好,但一些網站將被安全的地方應該有「https://」。所以我們如何才能將這種類型與普通網站區分開來 – Hulk 2012-07-26 14:07:19