手动缓存AppFabric中的MVC视图

Kev*_*yer 5 c# asp.net-mvc appfabric appfabric-cache

我试图通过自己缓存视图结果对象来重新创建MVC 4中OutputCache操作过滤器的大部分功能.我不想使用OutputCache动作过滤器的原因是因为我不能将它与AppFabric和部分视图一起使用; 部分视图始终存储在MemoryCache中,我希望在服务器场中使用缓存的对象.

我遇到的第一个问题是

{"Type 'System.Web.Mvc.TempDataDictionary' cannot be serialized. 
Consider marking it with the DataContractAttribute attribute, and marking all of 
its members you want serialized with the DataMemberAttribute attribute.  
If the type is a collection, consider marking it with the 
CollectionDataContractAttribute.  See the Microsoft .NET Framework documentation for  
other supported types."}
Run Code Online (Sandbox Code Playgroud)

这让我想知道是否应该缓存其他内容以返回最终的视图.有没有人知道我应该缓存什么来重新创建视图或不同的方法来缓存服务器场上的部分视图?我不想为此使用第三方插件.

谢谢

更新:我开始缓存部分视图的字符串表示,如下所示:

using (StringWriter sw = new StringWriter())
        {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, "ViewName");
            ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);
            view = sw.GetStringBuilder().ToString();
        }
Run Code Online (Sandbox Code Playgroud)

这使得在缓存中检索字符串并将其作为操作中的内容返回很容易.我仍在寻找其他建议或更好的方法来做到这一点.

Cyb*_*axs 0

也许有点晚了,但让我与你分享我的经验。

虽然 ASP.NET MVC 构建在 ASP.NET 框架之上,但它有一些相当显着的差异,导致在 MVC 中重用 ASP.NET 功能相当困难。你是对的:全页输出缓存和部分页面输出缓存是以完全不同的方式实现的。Greg Roberts 的另一篇博文指出 MVC 中的输出存在很多问题。它在 WebForms 中非常有用!

这就是为什么我转向 MvcDonutCaching ( Nuget )。它解决了我们的许多问题。请阅读此处codeplex上的介绍。

对您来说好消息是 MvcDonutCaching 也与 AppFabric Caching 完全兼容;DevTrends几个月前发布了一篇文章。这意味着您可以使用新的输出缓存提供程序(包含在 AppFabric 1.1 中)。

添加这个新的提供程序非常简单,只需以这种方式添加引用和更改配置即可。

<caching>
  <outputCache defaultProvider="DistributedCache">
    <providers>
      <add name="DistributedCache"
           type="Microsoft.Web.DistributedCache.DistributedCacheOutputCacheProvider, Microsoft.Web.DistributedCache"
           cacheName="default"
           dataCacheClientName="default" />
    </providers>
  </outputCache>
</caching>
Run Code Online (Sandbox Code Playgroud)

希望这对您有帮助,因为这对我们有很大帮助!