第一步, 在 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特性:
[OutputCache(CacheProfile = "StaticPage")]
public ActionResult Index()
{
return View();
}
第三部:为了便于修改缓存配置,我们可以办具体的缓存设置写在配置文件中,如下:
<caching>
<outputcachesettings>
<outputcacheprofiles>
<clear />
<!-- 24 hours-->
<add varybycustom="AnonymousID" varybyparam="*" duration="86400" name="StaticPage" />
</outputcacheprofiles>
</outputcachesettings>
</caching>