检查URL是否正常运行,是否要重定向到该URL本身,否则,如果不起作用,则重定向到另一个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;
   }
}