检查URL是否正常运行,是否要重定向到该URL本身,否则,如果不起作用,则重定向到另一个URL [英] checking if url is up and working, if it is to redirect to that url itself else if not working to redirect to another url
本文介绍了检查URL是否正常运行,是否要重定向到该URL本身,否则,如果不起作用,则重定向到另一个URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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)
{
Response.BufferOutput = true;
string url = "http://www.google.com";
bool str;
if (UrlIsValid(url))
{
str = true;
}
else
{
str = false;
}
if (str==true)
{
Response.Redirect(url);
}
else
{
Response.Redirect("http://www.yahoo.com");
}
无论给定的URL是否有效,它都会重定向到yahoo.如果我给了像Google这样的有效网址,我希望它重定向到google.
It redirects to yahoo regardless of whether the given url is valid or not. if i have given a valid url like google i want it to redirect to google.
推荐答案
这对我来说很好:
This works fine for me:
public static bool UrlIsValid(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Proxy = null;
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return true;
}
catch //If exception thrown then couldn't get response from address
{
return false;
}
}
private void Page_Load(object sender, EventArgs e)
{
Response.BufferOutput = true;
string url = "http://www.google.com";
if (UrlIsValid(url))
{
Response.Redirect(url);
}
else
{
Response.Redirect("http://www.yahoo.com");
}
}
您可以像这样检查URL(我将更改URL检查功能的正文):
You can check the URL like this (I will change the body of your URL-check function):
public static bool UrlIsValid(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Proxy = null;
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return true;
}
catch //If exception thrown then couldn't get response from address
{
return false;
}
}
这篇关于检查URL是否正常运行,是否要重定向到该URL本身,否则,如果不起作用,则重定向到另一个URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文