利用ResultFilter實現asp.net mvc 頁面靜態化

爲了提升網站性能、和網站的負載能力,頁面靜態化是一種有效的方式,這裏對於asp.net mvc3 構架下的網站,提供一種我的認爲比較好的靜態話方式。mvc

實現原理是經過mvc提供的過濾器擴展點實現頁面內容的文本保存,直接上代碼:app

public class StaticFileWriteFilterAttribute : FilterAttribute, IResultFilter
{
public void OnResultExecuted(ResultExecutedContext filterContext)
{asp.net

}ide

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; }
}this

public override bool CanSeek
{
get { return inner.CanSeek; }
}.net

public override bool CanWrite
{
get { return inner.CanWrite; }
}code

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
{

}
}
}
}

 

咱們的類StaticFileWriteFilterAttribute實現了IResultFilter,這個接口有兩個方法,OnResultExecuted和OnResultExecuting,其中OnResultExecuting是在controller中的action代碼執行完畢後,但viewresult執行以前(即頁面內容生成以前)執行;OnResultExecuted方法是在viewresult執行以後(即頁面內容生成以後)執行。

 

咱們在頁面生成以前將StaticFileWriteResponseFilterWrapper類註冊給Response對象的Filter屬性,這裏使用包裝類能夠在沒有反作用的狀況下注入頁面內容靜態化的代碼,對於處理業務邏輯的action是透明的。

 

 

 

 

 

歡迎轉載,轉載請保留原連接,如發現版權問題請及時聯繫我

小尾魚的池塘:http://www.cnblogs.com/xiaoweiyu/

相關文章
相關標籤/搜索