需要从OnResultExecuted获取操作属性

时间:2014-02-05 01:06:13

标签: c# asp.net-mvc-4

我有一个全局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变量中获取操作及其属性。

2 个答案:

答案 0 :(得分:4)

这个答案适用于MVC4,因为MVC5有filter overrides

似乎没有一种干净的方式(我避免反思。哎呀!)从ActionDescriptor获取OnResultExecuted

与您提供的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();
}

检查响应标头以验证

答案 1 :(得分:0)

试试这个

filterContext.Controller.GetType().GetMethod(action).GetCustomAttributes(typeof(OutputCacheAttribute), true).Length == 0