如果链接不起作用,我想生成特定链接的所有错误,那么它应该显示特定的 Web 服务器错误。
这是我的代码。请建议程序应该在哪里完成如果链接不起作用,我会得到所有错误
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
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>", "");
//strResult = strResult.Replace("<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" /><html xmlns="http://www.w3.org/1999/xhtml">");
div.InnerHtml = strResult;
}
protected void btn_createlink_Click(object sender, EventArgs e)
{
var links = TextBox1.Text.Split(new string[] { "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var link in links)
{
if (!IsLinkWorking(link))
{
//Here you can show the error. You don't specify how you want to show it.
TextBox2.Text += string.Format("{0}\nNot working\n\n ", link);
}
else
{
TextBox2.Text += string.Format("{0}\n working\n\n", link);
}
}
}
bool IsLinkWorking(string url)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
//You can set some parameters in the "request" object...
request.AllowAutoRedirect = true;
ServicePointManager.ServerCertificateValidationCallback = (s, cert, chain, ssl) => true;
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return true;
}
catch
{
//TODO: Check for the right exception here
return false;
}
}