包仔這幾天正好玩到網頁回應碼的部份,在ASP.NET中可以用HttpWebRequest、HttpWebResponse來達到,可是目前包仔就遇到一個特殊的問題,包仔在一網頁中欲取得該網頁之回應碼時,正巧此頁面是轉頁重新導向至他處,所以包仔再怎麼取都只是取到導向後頁面的內容。
在包仔百思不得其解時,在MSDN上面剛好找到說明,且看包仔分解:
包仔這幾天正好玩到網頁回應碼的部份,在ASP.NET中可以用HttpWebRequest、HttpWebResponse來達到,可是目前包仔就遇到一個特殊的問題,包仔在一網頁中欲取得該網頁之回應碼時,正巧此頁面是轉頁重新導向至他處,所以包仔再怎麼取都只是取到導向後頁面的內容。
在包仔百思不得其解時,在MSDN上面剛好找到說明,且看包仔分解:
transPage.aspx.cs(重新導向網頁)
CatchHttpCode.aspx.cs(實作網頁)
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public partial class CatchHttpCode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(CodeCatch("http://localhost/Mytest/transPage.aspx"));
}
private String CodeCatch(string URL)
{
HttpWebRequest regPage = (HttpWebRequest)WebRequest.Create(URL);
try
{
regPage.AllowAutoRedirect = false;//設定此要求不需跟隨導向網址重新要求
HttpWebResponse rspPage = (HttpWebResponse)regPage.GetResponse();
string catchCode = rspPage.StatusCode.GetHashCode().ToString();
rspPage.Close();
return catchCode;
}
catch (WebException e)
{
return e.Message + ",FAILED";
}
}
}
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public partial class CatchHttpCode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(CodeCatch("http://localhost/Mytest/transPage.aspx"));
}
private String CodeCatch(string URL)
{
HttpWebRequest regPage = (HttpWebRequest)WebRequest.Create(URL);
try
{
regPage.AllowAutoRedirect = false;//設定此要求不需跟隨導向網址重新要求
HttpWebResponse rspPage = (HttpWebResponse)regPage.GetResponse();
string catchCode = rspPage.StatusCode.GetHashCode().ToString();
rspPage.Close();
return catchCode;
}
catch (WebException e)
{
return e.Message + ",FAILED";
}
}
}
如此作法便可取得重新導向前的回應碼囉!!