【问题标题】: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
【发布时间】:2010-07-18 07:18:57
【问题描述】:

命名空间 WebApplication4 { 公共部分类_默认: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 响应 = (HttpWebResponse)wr.GetResponse ()) { 如果(response.StatusCode == HttpStatusCode.OK) { response.Close();

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

当我给谷歌时,它会重定向到谷歌,但是当我给一个无效的网址时,它不会重定向到雅虎,就像我给的一样。我在重定向之前给出了响应

【问题讨论】:

    标签: c# .net url


    【解决方案1】:

    您的 UrlIsValid 采用名为 smtpHost 的参数,表明它适用于 SMTP 邮件服务器。然后在其中,您尝试将整个 URL 解析为主机名。它根本行不通。

    您可以使用其中的 URL 创建一个新的 Uri 对象,然后创建一个 WebRequest 对象,请参见此处的示例:

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

    希望有帮助!

    【讨论】:

    • HttpWebResponse 实现了 IDisposable,因此您可以将其包装在 using 块中。
    • 感谢您的回复.. 但我希望它重定向。还有更多这不起作用..请建议如何重定向
    • 然后添加一个Response.Redirect,它将重定向到您选择的URL;您的问题显示了如何使用它。您能否再次尝试该代码并提供有关您遇到的问题的更多信息?我认为它很好地展示了这个概念
    • 我使用了代码但我不知道在哪里使用 response.redirect。然后我使用了 response.redirect(Uri) 它似乎不起作用
    • 我添加了代码,但它重定向到谷歌,但如果我提供错误的 url,它不会重定向到提供的第二个网站
    猜你喜欢
    • 1970-01-01
    • 2017-09-11
    • 2012-07-22
    • 1970-01-01
    • 2013-02-13
    • 2012-12-05
    • 2014-03-07
    • 1970-01-01
    • 2020-05-28
    相关资源
    最近更新 更多