我有一个全局 NoCache 过滤器,如下所示:https://stackoverflow.com/a/12964123/78739
这个全局无缓存过滤器适用于所有操作。我有一个案例,我需要允许使用 OutputCacheAttribute 缓存一个特定的操作。我在考虑在 NoCache 过滤器中检查刚刚执行的操作是否具有 OutputCacheAttribute。如果是这样,它不会应用无缓存设置。因此,例如,我的代码将是:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public sealed class NoCacheAttribute : FilterAttribute, IResultFilter
{
public void OnResultExecuted(ResultExecutedContext filterContext)
{
if (/* action does not have OutputCacheAttribute */)
{
var cache = filterContext.HttpContext.Response.Cache;
cache.SetCacheability(HttpCacheability.NoCache);
cache.SetRevalidation(HttpCacheRevalidation.ProxyCaches);
cache.SetExpires(DateTime.Now.AddYears(-5));
cache.AppendCacheExtension("private");
cache.AppendCacheExtension("no-cache=Set-Cookie");
cache.SetProxyMaxAge(TimeSpan.Zero);
}
}
}
问题是我不知道如何从传递到 OnResultExecuted 方法的 ResultExecutedContext 变量中获取操作及其属性。
最佳答案
这个答案是针对 MVC4 的,因为 MVC5 有 filter overrides
从 OnResultExecuted
ActionDescriptor
似乎没有一个干净的方法(我避免反射。讨厌!)
与您提供的 SO 链接中未接受的答案相反,OutputCacheAttribute 确实控制客户端缓存,因此:
在全局范围内
filters.Add(new OutputCacheAttribute { Location = OutputCacheLocation.None, NoStore = true });
然后在行动
//The OutputCacheAttribute in the global filter won't be called
//Only this OutputCacheAttribute is called since AllowMultiple in OutputCacheAttribute is false
[[OutputCacheAttribute(Location = OutputCacheLocation.Server, Duration = 100)]
public ActionResult Index()
{
return View();
}
检查响应 header 以验证
关于c# - 需要从 OnResultExecuted 获取 Action 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21566756/