Uri.IsWellFormedUriString返回true,但无法从url读取

时间:2013-10-28 13:34:22

标签: c# uri

我正在尝试通过以下方法检查网址http://master.dev.brandgear.net是否有效:

private bool UrlIsValid(string url)
        {
            using (var webClient = new WebClient())
            {
                bool response;
                try
                {
                    webClient.UseDefaultCredentials = true;
                    using (Stream strm = webClient.OpenRead(url))
                    {
                        response = true;
                    }
                }

                catch (WebException we)
                {
                    response = false;
                }

                return response;
            }
        }

但是,我收到了网络异常"404 not found."。我用Uri.IsWellFormedUriString检查了uri,它返回true。但是,可以通过浏览器打开相同的URL。知道如何验证吗?

2 个答案:

答案 0 :(得分:2)

我使用以下网址http://master.dev.brandgear.net运行了您的示例,并且还引发了异常。如果您在浏览器中打开相同的URL(例如Firefox)并运行Firebug插件,请打开“网络”选项卡,您将看到错误404(找不到页面)。您的代码没问题,但服务器返回404。

答案 1 :(得分:0)

要真正得到响应,当404异常发生时,你必须使用WebException而不是GetResponse或GetResponseStream方法。在这些情况下也要使用HttpWebRequest和HttpWebResponse来更好地控制,所以在异常发生后你检查它的状态以查看是否它是一个ProtocolError,如果有的话,从那里得到响应:

    private bool UrlIsValid(string url)
    {
        bool response = false;
        HttpWebResponse rep = null;

        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            rep = (HttpWebResponse)request.GetResponse();
        }
        catch (WebException we)
        {
            if (we.Status == WebExceptionStatus.ProtocolError)
                rep = (HttpWebResponse)we.Response;
        }

        if (rep != null)
        {
            try
            {
                using (Stream strm = rep.GetResponseStream())
                {
                    response = true;
                }
            }
            catch (WebException ex)
            {
                //no need variable is already false if we didnt succeed.
                //response = false;
            }
        }

        return response;
    }