避免在 ASP.NET MVC 5 应用程序的 Action 上使用 OnResultExecuted Filter

Avoid OnResultExecuted Filter on ASP.NET MVC 5 application's Action

我正在开发一个 MVC5 应用程序,它有一个 OnResultExecuted 过滤器,它总是将响应缓存设置为 "no-cache no-store":

public class NoCacheActionFilter : ActionFilterAttribute
{       
    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
        DateTime now = DateTime.UtcNow;

        cache.SetCacheability(HttpCacheability.NoCache);
        cache.SetExpires(now.AddDays(-1));
        cache.SetNoStore();

        base.OnResultExecuted(filterContext);
    }
}

但是我有一个 Action 需要缓存它的结果,所以我在上面设置了 OutputCahce 属性。

[OutputCache(Duration =300, Location =System.Web.UI.OutputCacheLocation.Client)]

但是,由于过滤器,它永远不会被缓存。

我的问题是是否有办法避免仅针对该操作的过滤器。

谢谢。

好吧,既然这个问题的答案被删除了……我不知道为什么……我打算 post 对我有用的解决方案。我留下答案是因为我认为知道还有另一种避免默认全局过滤器的方法比在完全有效的解决方案 posted here 中实现 "dumb" 属性更有趣。

第一:此解决方案仅有效,因为 OutputCacheAttribute "AllowMultiple" 设置为 false,因此可以替换 NoCacheActionFilter 并在全局过滤器中添加 OutputCacheAttribute,如

filters.Add(new OutputCacheAttribute { Location = OutputCacheLocation.None, NoStore = true, Duration = 0, VaryByParam = "*" });

然后如果我在操作级别添加 OutputCacheAttribute,它将替换之前配置的全局默认 OutputCache 过滤器(因为它已将 AllowMultiple 设置为 false)。

[OutputCache(Duration =300, VaryByParam = "param")]
public FileContentResult WhateverWithCache(string param)
{}

旁注:

OutputCacheAttribute中的"AllowMultiple"属性是一个属性,可以在C#实现的任何属性中定义,告诉属性是否可以多次设置一个单个元素。更多信息 here