這篇文章我來講兩個關於頁面最佳化的基本用法,下篇分析下靜態頁面緩衝的用法。現在雖然大家的上網環境好了很多,但網站越來越流利胖用戶端,使得頁面載入速度並沒有提高多少,所以如何提高響應速度也就成了大家各顯身手的地方了。
第一:OutputCacheAttribute,這個頁面級的緩衝我想大家用過web form開發的程式員都知道,它可以將整個頁面全部緩衝下來,同時支援多種參數形式以及到期策略。在asp.net mvc 1.0之前的預覽版中,好像沒有發現這東西,預覽版本太多,如有不實還請諒解,OutputCacheAttribute到了1.0後正式加入架構。先看下它的源碼,主要是OnResultExecuting這個方法,Duration屬性工作表示到期時間,VaryByParam屬性工作表示緩衝是否與參數有關係。
代碼
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited=true, AllowMultiple=false)]
public class OutputCacheAttribute : ActionFilterAttribute
{
// Fields
private OutputCacheParameters _cacheSettings;
// Methods
public OutputCacheAttribute();
public override void OnResultExecuting(ResultExecutingContext filterContext);
// Properties
public string CacheProfile { get; set; }
internal OutputCacheParameters CacheSettings { get; }
public int Duration { get; set; }
public OutputCacheLocation Location { get; set; }
public bool NoStore { get; set; }
public string SqlDependency { get; set; }
public string VaryByContentEncoding { get; set; }
public string VaryByCustom { get; set; }
public string VaryByHeader { get; set; }
public string VaryByParam { get; set; }
// Nested Types
private sealed class OutputCachedPage : Page
{
// Fields
private OutputCacheParameters _cacheSettings;
// Methods
public OutputCachedPage(OutputCacheParameters cacheSettings);
protected override void FrameworkInitialize();
}
}
OutputCacheAttribute用法非常簡單:
1:直接寫在Controller中,例如:
但不推薦這樣寫,因為緩衝參數寫在代碼中,不方便以後更改。
[OutputCache(Duration = 10, VaryByParam = "none")]
public ActionResult Index()
{
return View();
}
2:可以寫在頁面中:<%@ OutputCache Duration="10" VaryByParam="None" %>。
3:可以寫在設定檔中:需要兩個步驟。
1>:在Controller代碼是加上緩衝特性。
[OutputCache(CacheProfile = "MyProfile")]
public ActionResult Index()
2>:Web.Config配置如下:name就是Controller代碼中的CacheProfile。
代碼
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="MyProfile" duration="60" varyByParam="*" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
第二:CompressAttribute。一般大型網站在做最佳化時,除了程式端的最佳化外,還有伺服器端。常見方法之一是啟用gzip壓縮。在程式中我們也可以實現,且難度不大。原理就是在
Response.Filter Stream 上加個 GZipStream/DeflateStream。
代碼
public class CompressAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var acceptEncoding = filterContext.HttpContext.Request.Headers["Accept-Encoding"];
if (!string.IsNullOrEmpty(acceptEncoding))
{
acceptEncoding = acceptEncoding.ToLower();
var response = filterContext.HttpContext.Response;
if (acceptEncoding.Contains("gzip"))
{
response.AppendHeader("Content-encoding", "gzip");
response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
}
else if (acceptEncoding.Contains("deflate"))
{
response.AppendHeader("Content-encoding", "deflate");
response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
}
}
}
}
我們來看下啟用壓縮前後的效果:我們用firebug觀察下頁面大小。
這是沒有啟用壓縮時的圖。
這是啟用壓縮後的。儘管我這個頁面本來就較小,儘管在載入時間上看不出問題,但頁面很明顯變小了,大的頁面在時間載入上會有更加明顯的效果。