不知道大家有没有注意过google和baidu首页页面的html,打开一看你会发现,竟然没有缩排什么,几乎整个页面输出都快写成一行了,至于为什么这样做,我能想到的是节省流量,没别的想法了.那我们是不是也可以做到这样呢(虽然我们对流量没什么要求),当然是可以的,写代码的时候不要缩排,把html全部写在一行不就行了,当然这个方法的确可行,但是麻烦了点,而且维护起来也不方便.有没有更好的办法,当然是有,我们就利用HttpModule和Response.Filter来实现这个功能吧,废话说完了,切入正题.
既然是用HttpModule,那当然就得弄个实现了IHttpModule的类了:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
namespace K2046.Handlers
{
public class FilterModule : IHttpModule
{
IHttpModule 成员#region IHttpModule 成员
public void Dispose()
{
// Do Nothing.
}
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(Application_BeginRequest);
}
void Application_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
if (true)//这里看情况加上你的条件,要不然所有的请求都会被处理,会造成其它文件类型的输出异常.
{
app.Response.Filter = new ResponseFilter(app.Response.Filter);
}
}
#endregion
}
}
web.Config的<system.web>中再加上如下代码:
<httpModules>
<add name="ResponseFilter" type="K2046.Handlers.FilterModule, K2046.Handlers"/>
</httpModules>
≡谡饫锩嬗玫搅艘桓鯮esponseFilter的类,这个也是自己实现的,代码如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
namespace K2046.Handlers
{
public class ResponseFilter : Stream
{
private Stream _StreamFilter;
private ResponseFilter() { }
public ResponseFilter(Stream stream)
{
_StreamFilter = stream;
}
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return true; }
}
public override bool CanWrite
{
get { return true; }
}
public override void Flush()
{
_StreamFilter.Flush();
}
public override long Length
{
get
{
return _StreamFilter.Length;
}
}
public override long Position
{
get
{
return _StreamFilter.Position;
}
set
{
_StreamFilter.Position = value;
}
}
public override int Read(byte[] buffer, int offset, int count)
{
return _StreamFilter.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return _StreamFilter.Seek(offset, origin);
}
public override void SetLength(long value)
{
_StreamFilter.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
string Html = Encoding.UTF8.GetString(buffer);
Html = Regex.Replace(Html, @">\s+?<", "><"); //去除Html中的空白字符.
Html = Regex.Replace(Html, @"\r\n\s*", "");
Html = Regex.Replace(Html, @"<body([\s|\S]*?)>([\s|\S]*?)</body>", @"<body$1>$2<!--Hello,Robot!--></body>", RegexOptions.IgnoreCase);
buffer = Encoding.UTF8.GetBytes(Html);
_StreamFilter.Write(buffer, offset, buffer.Length);
}
}
}