第一步, 在 global.asax.cs 文件中 overite GetVaryByCustomString函數:緩存
/// <summary> /// 自定義生成的依據 /// </summary> /// <param name="context"></param> /// <param name="custom"></param> /// <returns></returns> public override string GetVaryByCustomString(HttpContext context, string custom) { if (EqualsIgnoreCase("AnonymousID", custom)) { return context.Request.AnonymousID; } return base.GetVaryByCustomString(context, custom); } // System.Web.Util.StringUtil static bool EqualsIgnoreCase(string s1, string s2) { return (string.IsNullOrEmpty(s1) && string.IsNullOrEmpty(s2)) || (!string.IsNullOrEmpty(s1) && !string.IsNullOrEmpty(s2) && s2.Length == s1.Length && string.Compare(s1, 0, s2, 0, s2.Length, StringComparison.OrdinalIgnoreCase) == 0); }
第二步:在須要輸出緩存的Action上添加OutPutCache特性:mvc
[OutputCache(CacheProfile = "StaticPage")] public ActionResult Index() { return View(); }
第三部:爲了便於修改緩存配置,咱們能夠辦具體的緩存設置寫在配置文件中,以下:ide
<caching> <outputcachesettings> <outputcacheprofiles> <clear /> <!-- 24 hours--> <add varybycustom="AnonymousID" varybyparam="*" duration="86400" name="StaticPage" /> </outputcacheprofiles> </outputcachesettings> </caching>