部分缓存剃刀助手

时间:2015-11-10 14:08:50

标签: asp.net-mvc caching razor

在WebForm控件中,我可以使用OutputCache行缓存单个控件的响应,例如:

<%@ OutputCache Duration="240" VaryByParam="none" VaryByCustom="none" %>

如何使用Razor助手进行相同操作?

@Helper HelperName(Vars)
    ' Do stuff, and cache it, return from cache as per parameters etc
End Helper

2 个答案:

答案 0 :(得分:2)

在Asp.Net Mvc 6中,您可以使用<cache>标记帮助程序来缓存部分视图。

<cache expires-after="@TimeSpan.FromMinutes(10)">
    @Html.Partial("_WhatsNew")
    *last updated  @DateTime.Now.ToLongTimeString()
</cache>

http://blogs.msdn.com/b/cdndevs/archive/2015/08/06/a-complete-guide-to-the-mvc-6-tag-helpers.aspx

答案 1 :(得分:1)

  1. 使用子操作,这将允许您以与使用WebForm控件相同的方式使用[OutputCache]属性。

  2. 利用System.Runtime.Caching进行内存缓存。请参阅:https://msdn.microsoft.com/en-us/library/vstudio/ff477235%28v=vs.100%29.aspx?f=255&MSPPError=-2147217396

  3. 但是,即使您使用#2,我也建议您将代码移到实际的HtmlHelper扩展名中,而不是使用Razor Helpers。我不确定为什么微软甚至会让这些成为可能,但它们应该像瘟疫一样避免。它们直到运行时才编译,这意味着如果您有错误,只有在正确的情况下访问正确的页面时才会发现它,而不是在构建期间立即得到通知。更糟糕的是,几乎不可能测试Razor助手,这使得你更有可能引入爆炸性的bug。