HTTP头部和正文
因为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中可以设置返回给浏览器的头部信息,尽量去掉无用的头部信息以减少流量