Shweta
Shweta

Reputation: 51

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

namespace 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); 

using (HttpWebResponse response = (HttpWebResponse)wr.GetResponse ()) { if (response.StatusCode == HttpStatusCode.OK) { response.Close();

    Response.Redirect(url);
}
else
{
    Response.Redirect("http://www.yahoo.com");
}

when i give google it redirects to google but when i giv an invalid url it doesn redirect to yahoo lik hw i hav given. i gave the response before redirect

Upvotes: 2

Views: 3395

Answers (1)

Kieren Johnstone
Kieren Johnstone

Reputation: 42003

Your UrlIsValid takes a parameter called smtpHost, suggesting it works with SMTP mail servers. Then within it, you attempt to resolve the entire URL as a hostname. It simply won't work at all.

You could create a new Uri object with the URL in, then create a WebRequest object, see the example here:

http://msdn.microsoft.com/en-us/library/system.uri.aspx

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();
}

Hope that helps!

Upvotes: 1

Related Questions