列出 OutputCache 條目
在我的 asp.net mvc 應用程序中,我在不同的操作方法上使用了 OutputCache 屬性。是否可以查看與 OutputCache 屬性相關的記憶體中的目前條目?如果我 cicle on
System.Web.HttpContext.Current.Cache我找不到這種類型的條目。在此先感謝 F。
輸出記憶體不可公開訪問,因此您不會在
System.Web.HttpContext.Current.Cache. 在 ASP.NET 2 中,它包含在CacheInternal’_caches成員中,您可以通過名稱猜到它是內部抽像類的私有成員。可以通過反射來檢索它,儘管這不是一件容易的事。此外,如果您檢索它,您會看到它包含各種內部記憶體條目,如配置文件路徑記憶體、動態生成的類記憶體、移動功能、原始響應記憶體(這是輸出記憶體項的類型)。
假設您可以過濾與輸出記憶體相關的項目。問題是除了密鑰和原始響應(作為字節數組)之外,它們不包含太多人類可讀的資訊。如果我使用了 GET (a1) 或 POST (a2) 方法,則密鑰通常包含資訊、站點名稱、根相對 url 和相關參數的雜湊值。
我想這是一個常見的痛點,因此在 ASP.NET 4 中引入了自定義輸出記憶體提供程序的新概念。您可以實現自己的輸出記憶體提供程序,繼承自 OutputCacheProvider 並提供返回所有條目的方法。您可以查看這篇文章 - http://weblogs.asp.net/gunnarpeipman/archive/2009/11/19/asp-net-4-0-writing-custom-output-cache-providers.aspx。我個人還沒有研究過新的 OutputCache 基礎設施,所以如果你發現了什麼,寫下來會很有趣。
這是檢索內部記憶體條目的程式碼。您可以在 Visual Studio 中調試時瀏覽它們的值:
Type runtimeType = typeof(HttpRuntime); PropertyInfo ci = runtimeType.GetProperty( "CacheInternal", BindingFlags.NonPublic | BindingFlags.Static); Object cache = ci.GetValue(ci, new object[0]); FieldInfo cachesInfo = cache.GetType().GetField( "_caches", BindingFlags.NonPublic | BindingFlags.Instance); object cacheEntries = cachesInfo.GetValue(cache); List<object> outputCacheEntries = new List<object>(); foreach (Object singleCache in cacheEntries as Array) { FieldInfo singleCacheInfo = singleCache.GetType().GetField("_entries", BindingFlags.NonPublic | BindingFlags.Instance); object entries = singleCacheInfo.GetValue(singleCache); foreach (DictionaryEntry cacheEntry in entries as Hashtable) { FieldInfo cacheEntryInfo = cacheEntry.Value.GetType().GetField("_value", BindingFlags.NonPublic | BindingFlags.Instance); object value = cacheEntryInfo.GetValue(cacheEntry.Value); if (value.GetType().Name == "CachedRawResponse") { outputCacheEntries.Add(value); } } }