如何检查URL是否有效

时间:2013-04-18 09:49:39

标签: c# asp.net

我在该用户中输入了一个文本框,但是如果要在页面呈现时检查该URL,那么该怎么办?

这是我的代码:

protected void btnRender_Click(object sender, EventArgs e)
{
    string strResult = string.Empty;
    WebResponse objResponse;
    WebRequest objRequest = System.Net.HttpWebRequest.Create(urltxt.Text);
    objResponse = objRequest.GetResponse();
    using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
    {
        strResult = sr.ReadToEnd();
        sr.Close();
    }
    strResult = strResult.Replace("<form id='form1' method='post' action=''>", "");
    strResult = strResult.Replace("</form>", "");          
    TextBox1.Text = strResult.Trim();
    div.InnerHtml = strResult.Trim();
}

我有这个代码来检查URL是否有效,所以你能告诉我在哪里调用它吗? {如果我还要检查https,那么我该如何处理此代码}

 protected bool CheckUrlExists(string url)
    {
        // If the url does not contain Http. Add it.
      // if i want to also check for https how can i do.this code is only for http not https
        if (!url.Contains("http://"))
        {
            url = "http://" + url;
        }
        try
        {
            var request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "HEAD";
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                return response.StatusCode == HttpStatusCode.OK;
            }
         }
         catch
         {
             return false;
         }
     }

TextBox名称是urltxt

2 个答案:

答案 0 :(得分:3)

试试这个uriName(您想要的URI)

  bool Uriresult = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) && uriName.Scheme == Uri.UriSchemeHttp;

根据您的代码

string uriName = urltxt.Text; bool Uriresult = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) && uriName.Scheme == Uri.UriSchemeHttp;

答案 1 :(得分:2)

尝试如下,它会帮助你......

     protected void btnRender_Click(object sender, EventArgs e)
        {
            if(CheckUrlExists(urltxt.Text))
            {
                string strResult = string.Empty;
                WebResponse objResponse;
                WebRequest objRequest = System.Net.HttpWebRequest.Create(urltxt.Text);
                objResponse = objRequest.GetResponse();
                using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
                {
                    strResult = sr.ReadToEnd();
                    sr.Close();
                }
                strResult = strResult.Replace("<form id='form1' method='post' action=''>", "");
                strResult = strResult.Replace("</form>", "");
                TextBox1.Text = strResult.Trim();
                div.InnerHtml = strResult.Trim();
            }
            else
            {
                MessageBox.Show("Not a Valid URL");
            }
        }