命名空间WebApplication4 { public partial class _Default:System.Web.UI.Page {
public static bool UrlIsValid(string url)
{
bool br = false;
try
{
IPHostEntry ipHost = Dns.Resolve(url);
br = true;
}
catch (SocketException)
{
br = false;
}
return br;
}
private void Page_Load(object sender, EventArgs e)
{
string url = "http://www.srv123.com";
WebRequest wr = WebRequest.Create(url);
使用(HttpWebResponse response =(HttpWebResponse)wr.GetResponse()) { if(response.StatusCode == HttpStatusCode.OK) { response.Close();
Response.Redirect(url);
}
else
{
Response.Redirect("http://www.yahoo.com");
}
当我给谷歌它重定向到谷歌,但当我给一个无效的网址,它没有重定向到雅虎喜欢我给我。我在重定向之前给出了回复
答案 0 :(得分:1)
您的UrlIsValid采用名为smtpHost
的参数,表明它适用于SMTP邮件服务器。然后在其中,您尝试将整个URL解析为主机名。它完全不起作用。
您可以创建一个包含URL的新Uri
对象,然后创建一个WebRequest
对象,请参阅此处的示例:
Uri siteUri = new Uri("http://www.contoso.com/");
WebRequest wr = WebRequest.Create(siteUri);
// now, request the URL from the server, to check it is valid and works
using (HttpWebResponse response = (HttpWebResponse)wr.GetResponse ())
{
if (response.StatusCode == HttpStatusCode.OK)
{
// if the code execution gets here, the URL is valid and is up/works
}
response.Close();
}
希望有所帮助!