【问题标题】:Need to get the action attributes from OnResultExecuted需要从 OnResultExecuted 中获取动作属性
【发布时间】:2014-03-01 06:21:03
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    此答案适用于 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();
    }
    

    检查响应标头进行验证

    【讨论】:

    • 过滤器覆盖的用途有限,因为它们不允许您选择性地覆盖过滤器。他们强迫你剔除某种类型的所有过滤器,这可能不是你想要的
    【解决方案2】:

    试试这个

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

    【讨论】:

    • 这个“动作”从何而来?
    猜你喜欢
    • 2021-10-24
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    • 1970-01-01
    相关资源
    最近更新 更多