因為response.OutputStream返回的HttpResponseStream為不能讀只能寫的流,故要擷取其中的資料只能另想辦法了,通過reflector可以發現可以用反射的方式截取其中的內容:
response內容:
private TextWriter tw_new, tw_old;
private StringBuilder _content;
private FieldInfo tw_field;
BeginRequest事件中:
_content = new StringBuilder();
tw_old = _contextApplication.Response.Output;
tw_new = new StringWriter(_content);
var type_rp = _contextApplication.Response.GetType();
tw_field = type_rp.GetField("_writer", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
tw_field.SetValue(_contextApplication.Response, tw_new);//重新設定_write(TextWrite)的欄位為tw_new,這樣response.write就寫寫入到_content中
EndRequest事件中:
tw_field.SetValue(_contextApplication.Response, tw_old);//還原TextWrite _write還原
if (!string.IsNullOrEmpty(_content.ToString()))
{
_contextApplication.Response.Write(_content.ToString());//輸入到頁面_content為頁面內容
}
頭部:
1.擷取HttpWorkerRequest類:
HttpWorkerRequest m_workRequest = GetWorkerRequest();
private HttpWorkerRequest GetWorkerRequest()
{
IServiceProvider m_provider = HttpContext.Current;
return ((HttpWorkerRequest)m_provider.GetService(typeof(HttpWorkerRequest)));
}
2.反射擷取request頭部:
FieldInfo test=m_workRequest.GetType().GetField("_allRawHeaders", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (test != null)
{
string mm = test.GetValue(m_workRequest) as string;//得到頭部資訊
}
當然也可以通過:
string head = string.Empty;
for (int i = 0; i < request.Headers.Count; i++)
{
head += request.Headers.GetKey(i) + ":" + request.Headers[i]+"\n";
}
3.擷取頁面中設定過 的resonse頭部
在通過reflector觀看代碼過程中,無法擷取到系統返回給用戶端的代碼,只能擷取我們自己在頁面中設定的頭部資訊,reponse頭部分兩種,分別對應兩個欄位
_customHeaders(自訂頭部)_cacheHeaders緩衝頭部(如Expires)
response.AddHeader("aaa", "aa");//自訂頭部
response.AddHeader("Expires", "2012-01-01");//需要緩衝的頭部
//response.AddHeader("Content-Type", "text/xml");
FieldInfo field_ResponseHeader = response.GetType().GetField("_customHeaders", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
FieldInfo field_ResponseHeader2 = response.GetType().GetField("_cacheHeaders", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (field_ResponseHeader != null)
{
ArrayList collection = field_ResponseHeader.GetValue(response) as ArrayList;//擷取自訂的值
ArrayList collection2 = field_ResponseHeader2.GetValue(response) as ArrayList;//擷取緩衝頭部添加的值
}
IIS中可以設定返回給瀏覽器的頭部資訊,盡量去掉無用的頭部資訊以減少流量