首页 > 代码库 > 利用ResultFilter实现asp.net mvc 页面静态化
利用ResultFilter实现asp.net mvc 页面静态化
为了提高网站性能、和网站的负载能力,页面静态化是一种有效的方式,这里对于asp.net mvc3 构架下的网站,提供一种个人认为比较好的静态话方式。
实现原理是通过mvc提供的过滤器扩展点实现页面内容的文本保存,直接上代码:
public class StaticFileWriteFilterAttribute : FilterAttribute, IResultFilter
{
public void OnResultExecuted(ResultExecutedContext filterContext)
{
}
public void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.HttpContext.Response.Filter = new StaticFileWriteResponseFilterWrapper(filterContext.HttpContext.Response.Filter, filterContext);
}
class StaticFileWriteResponseFilterWrapper : System.IO.Stream
{
private System.IO.Stream inner;
private ControllerContext context;
public StaticFileWriteResponseFilterWrapper(System.IO.Stream s,ControllerContext context)
{
this.inner = s;
this.context = context;
}
public override bool CanRead
{
get { return inner.CanRead; }
}
public override bool CanSeek
{
get { return inner.CanSeek; }
}
public override bool CanWrite
{
get { return inner.CanWrite; }
}
public override void Flush()
{
inner.Flush();
}
public override long Length
{
get { return inner.Length; }
}
public override long Position
{
get
{
return inner.Position;
}
set
{
inner.Position = value;
}
}
public override int Read(byte[] buffer, int offset, int count)
{
return inner.Read(buffer, offset, count);
}
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
return inner.Seek(offset, origin);
}
public override void SetLength(long value)
{
inner.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
inner.Write(buffer, offset, count);
try
{
string p = context.HttpContext.Server.MapPath(HttpContext.Current.Request.Path);
if (Path.HasExtension(p))
{
string dir = Path.GetDirectoryName(p);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
if (File.Exists(p))
{
File.Delete(p);
}
File.AppendAllText(p, System.Text.Encoding.UTF8.GetString(buffer));
}
}
catch
{
}
}
}
}
利用ResultFilter实现asp.net mvc 页面静态化