c# - 需要从 OnResultExecuted 获取 Action 属性

标签 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 变量中获取操作及其属性。

最佳答案

这个答案是针对 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/

相关文章:

c# - ASP.NET Core MVC 应用程序发布时的奇怪行为

c# - 将 unsigned long long 从 C++ 服务器流式传输到 C# 客户端

c# - 未将对象引用设置为对象(从 View 调用 Razor 模型)

c# - 使用 Entity Framework 将具有新角色的用户更新到数据库中

C# 在 mvc - 4 项目中为客户端用户资源文件的最佳方式

c# - 带字符串的动态 LINQ?

c# - 使用 C# 在每一行中动态地将 Button 添加到 ListView

c# - 将文件上传到 Azure Blob 存储

c# - 如何在节点树中找到 NodeData?

asp.net-mvc - ASP.NET MVC 4 - Twitter Bootstrap 渲染问题