在MVC 3中扩展OutputCacheAttribute

时间:2011-07-27 02:16:10

标签: asp.net-mvc asp.net-mvc-3

OutputCacheAttribute使用什么缓存机制以及如何扩展它?

1 个答案:

答案 0 :(得分:0)

它使用ASP.NET WebForm缓存,您可以通过覆盖OnResultExecuting来扩展它。

参考:

从上面链接中提取代码。

public override void OnResultExecuting(ResultExecutingContext filterContext) {
    if (filterContext == null) {
      throw new ArgumentNullException("filterContext");
    }

    if (!filterContext.IsChildAction) {
        // we need to call ProcessRequest() since there's no other way to set the Page.Response intrinsic
        using (OutputCachedPage page = new OutputCachedPage(_cacheSettings)) {
            page.ProcessRequest(HttpContext.Current);
        }
    }
}

private sealed class OutputCachedPage : Page {
    private OutputCacheParameters _cacheSettings;

    public OutputCachedPage(OutputCacheParameters cacheSettings) {
        // Tracing requires Page IDs to be unique.
        ID = Guid.NewGuid().ToString();
        _cacheSettings = cacheSettings;
    }

    protected override void FrameworkInitialize() {
        // when you put the <%@ OutputCache %> directive on a page, the generated code calls InitOutputCache() from here
        base.FrameworkInitialize();
        InitOutputCache(_cacheSettings);
    }
}