Запрос, связанный с атрибутом [OutputCache]

Чтобы отключить кеш браузера, чтобы надежно указать браузеру не кэшировать, я обнаружил, что лучшим решением было создать собственный класс атрибутов [NoCache].

public class NoCacheSettingsAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        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);
    }
}

И глобальные настройки фильтра

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    // Makes sure that cached pages are not served to any browser including chrome
    filters.Add(new NoCacheSettingsAttribute());
}

Я хочу использовать [OutputCache(CacheProfile = "2Hour")] в некотором ActionResult контроллера, а также хочу использовать NoCacheSetting для остальной части контроллера глобально, скажем, в BaseController, ( все контроллеры наследуются от BaseController)

Так что вопрос в том, будет ли он нормально работать? Или я должен поставить остальные контроллеры 1 на один?


person Shubhajyoti Ghosh    schedule 23.11.2013    source источник


Ответы (1)


Почему бы просто не исключить действия контроллера, уже украшенные атрибутом OutputCache, из обработки:

public class NoCacheSettingsAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        var descriptor = new ReflectedControllerDescriptor(
            filterContext.Controller.GetType()
        );

        var action = descriptor.FindAction(
            filterContext.Controller.ControllerContext, 
            filterContext.RequestContext.RouteData.GetRequiredString("action")
        );

        if (!action.GetCustomAttributes(typeof(OutputCacheAttribute), true).Any())
        {
            // The controller action is not decorated with the 
            // [OutputCache] attribute, so you could apply your NoCache logic here

            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();
        }
    }
}
person Darin Dimitrov    schedule 23.11.2013
comment
@Darni Dimitrov: Не обязательно ставить base.OnResultExecuting(filterContext); ? - person Shubhajyoti Ghosh; 23.11.2013
comment
Нет, совершенно ненужно. - person Darin Dimitrov; 23.11.2013