我用我們採用的解決方案回答我自己的問題。
在我們的OutputCacheAttribute
中,我們添加一個空的緩存對象,其中包含一個取決於請求的URL和一些參數的鍵。這將用於使外部頁面無效。
然後,我們還添加另一個對象,其中包含一個取決於當前請求幷包含前一個cacheKey的鍵。
最後,建立一個靜態的ValidationCallback。回調獲取當前請求的關鍵字值,這是依賴關鍵字。然後,如果它不爲null,則獲取依賴項的值,如果爲null,則依賴項已被逐出,並將validationStatus
設置爲HttpValidationStatus.Invalid
。
一些代碼來說明:
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
base.OnResultExecuting(filterContext);
// Build dependencies
BuildDependencies(paramsToDepend, filterContext.Controller, this.Duration);
}
private void BuildDependencies(IEnumerable<string> paramsToDepend, ControllerBase controller, int duration)
{
string[] valuesToInclude = GetValuesToInclude(paramsToInclude, controller.ControllerContext);
// Build the caché key for the current request
var cacheKey = CacheKeyProvider.GetCacheKeyFor(controller, paramsToDepend);
var cache = controller.ControllerContext.HttpContext.Cache;
var cacheValue = cache.Get(cacheKey);
if (cacheValue == null)
{
// The key is created if not exists
Provider.Add(cacheKey, new object(), Context.CurrentDateTime.AddSeconds(duration).ToUniversalTime());
}
// Add the dependency
Provider.Set(CachePrefix + controller.ControllerContext.HttpContext.Request.Path, cacheKey, Context.CurrentDateTime.AddSeconds(duration).ToUniversalTime());
// Register callback
controller.ControllerContext.HttpContext.Response.Cache.AddValidationCallback(new HttpCacheValidateHandler(ValidationCallback), null);
}
public static void ValidationCallback(HttpContext context, object data, ref HttpValidationStatus validationStatus)
{
var provider = OutputCache.Providers[OutputCache.DefaultProviderName];
var dependency = provider.Get(CachePrefix + context.Request.RawUrl) as string;
if (dependency == null) return;
var depValue = provider.Get(dependency);
// If it's null, someone has invelidated the caché (an entity was modified)
if (depValue == null)
{
validationStatus = HttpValidationStatus.Invalid;
}
}