C# 在ChildAction中取消输出缓存

C# 在ChildAction中取消输出缓存,c#,asp.net-mvc,C#,Asp.net Mvc,有人知道是否可以取消代码中的输出缓存吗?我的意思是,如果我将输出缓存放在子操作上,如下所示,那么我可以基于一个条件从子操作内部取消该缓存吗 [ChildActionOnly] [OutputCache(Duration = 36000, VaryByParam="tagslug")] public virtual ActionResult MostViewed(string tagslug, int count) { // Make an API call here. If not da

有人知道是否可以取消代码中的输出缓存吗?我的意思是,如果我将输出缓存放在子操作上,如下所示,那么我可以基于一个条件从子操作内部取消该缓存吗

[ChildActionOnly]
[OutputCache(Duration = 36000, VaryByParam="tagslug")]
public virtual ActionResult MostViewed(string tagslug, int count)
{
    // Make an API call here. If not data returned do not cache the ChildAction as specified above
}
略读看起来唯一的逻辑是不缓存异常:

// Only cache output if this wasn't an error
if (!wasException) {
    ChildActionCacheInternal.Add(uniqueId, capturedText,
                                 DateTimeOffset.UtcNow.AddSeconds(Duration));
}
我看不出有什么好办法可以解决这个问题:我认为您必须根据CodePlex的ASP.NET MVC源代码中的原始源代码创建自己的自定义
OutputCachingAttribute
,然后为返回的输出在该行添加额外的检查,例如

if (!(wasException || capturedText.Contains("results:0"))) {
或者类似的方法,或者找到一种从控制器向该代码传递标志的方法。现有代码使用对象在会话上存储值;你可以复制这个

  • 定义与
    \u childActionFilterFinishCallbackKey
    相同的新静态对象键,例如
    \u noCacheResultKey
  • 将公共静态方法添加到可以调用的属性中,例如

    public static void FlagNoCache(HttpContext httpContext) {
        httpContext.Items[_noCacheResultKey] = true;
    }
    
  • 扩展
    ClearChildActionFilterFinishCallback
    以将其从
    .Items[]
    以及回调中删除
  • 扩展上述测试以检查这一点,例如

    if (!(wasException
          || filterContext.HttpContext.Items.ContainsKey(_noCacheResultKey))) {
    
  • 从控制器调用
    MyOutputCacheAttribute.FlagNoCache(上下文)如有必要

  • 也可以从代码中抛出一个异常,然后在另一个
    IEExceptionFilter
    中捕获它,这样它就不会被传递到
    OutputCacheAttribute
    之外,但我不知道有多抱歉