我们可以用OutputCache覆盖用MVC编写的NoCahe属性吗?

时间:2018-03-13 18:07:38

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

我正在使用ASP.Net MVC并像这样编写NoCacheAttribute

std::chrono::duration_cast<std::chrono::milliseconds>

然后我将它应用到我的baseController,我的所有web控制器都继承了它。

我想将OutputCache应用于我的一些控制器方法,但由于NoCacheAttribute已经应用于控制器类。如何使用OutPutCache覆盖NoCache

1 个答案:

答案 0 :(得分:0)

你可以简单地创建一个看起来像

的[IgnoreNoCacheAttribute]
public class IgnoreNoCacheAttribute: Attribute {}

然后你的NoCacheAttribute成为

  public class NoCacheAttribute : ActionFilterAttribute
    {

        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {

            bool ignoreNoCacheAttribute = filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(IgnoreNoCacheAttribute), true) ||
                                          filterContext.ActionDescriptor.IsDefined(typeof(IgnoreNoCacheAttribute), true);

            if (!ignoreNoCacheAttribute)
            {
                filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
                filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
                filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
                filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                filterContext.HttpContext.Response.Cache.SetNoStore();
            }

            base.OnResultExecuting(filterContext);
        }
    }