ASP.NET MVC 扩展性洞穴缓存(ASP.NET MVC Extensible Donut Caching)#
ASP.NET MVC Extensible Donut Caching 是一个专为ASP.NET MVC 3及以上版本设计的高级缓存解决方案。它允许您缓存整个页面,除了一个或多个需要在每次请求时执行的Html.Action
。这非常适合显示用户特定的内容。
下载和安装
最简便地将洞穴缓存添加到您的MVC项目中,是通过NuGet包管理器。在Visual Studio中,选择“工具”-> “库包管理器”,然后选择“包管理控制台”或“管理NuGet包”。在控制台中输入 install-package MvcDonutCaching
后回车。在GUI界面中,只需搜索 MvcDonutCaching
并点击安装按钮即可。
使用方法
该包为内置的Html.Action
HTML助手提供了几个重载方法。新的参数名为excludeFromParentCache
,将其设置为true
,表示任何不应被缓存的动作,或者应有不同于页面其余部分的缓存持续时间。
@Html.Action("Login", "Account", true)
此外,还提供了一个DonutOutputCacheAttribute
,可替换内置的OutputCacheAttribute
。这个属性通常放在需要被缓存的每个控制器动作上。
您可以指定固定的缓存期限:
[DonutOutputCache(Duration = "300")]
public ActionResult Index()
{
return View();
}
或者使用缓存配置文件:
[DonutOutputCache(CacheProfile = "FiveMins")]
public ActionResult Index()
{
return View();
}
如果使用缓存配置文件,请确保在web.config中进行配置,在system.web
元素内添加:
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="FiveMins" duration="300" varyByParam="*" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
您还可以配置输出缓存以使用自定义提供商:
<caching>
<outputCache defaultProvider="DistributedCacheProvider">
<providers>
<add name="DistributedCacheProvider" type="DevTrends.Example.DistributedCacheProvider" />
</providers>
</outputCache>
</caching>
请注意,本项目不包含自定义提供程序,但您可以轻松地通过继承System.Web.Caching.OutputCacheProvider
来编写。网络上有许多实现示例可供参考。
更多信息
有关ASP.NET MVC Extensible Donut Caching的详尽指南可在DevTrends博客上查阅。
项目特点
- 高度灵活:允许在页面的一部分进行动态更新,确保用户特定内容始终是最新的。
- 易于集成:通过简单的NuGet包安装,快速整合到现有ASP.NET MVC项目。
- 简化编码:提供额外的HTML助手方法和自定义特性,简化缓存控制。
- 自定义缓存策略:支持自定义缓存期限、缓存配置文件以及自定义缓存提供者。
借助ASP.NET MVC Extensible Donut Caching,您可以提升应用性能,优化用户体验,并且降低服务器负载,尤其是在处理大量用户和复杂数据的情况下。赶快尝试并享受它带来的便利吧!