Desactivar la caché del navegador para toda ASP.NET sitio web


Estoy buscando un método para desactivar la caché del navegador para un completo ASP.NET Sitio web de MVC

Encontré el siguiente método:

Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
Response.Cache.SetNoStore();

Y también un método meta tag (no funcionará para mí, ya que algunas acciones MVC envían HTML/JSON parcial a través de Ajax, sin una etiqueta meta head).

<meta http-equiv="PRAGMA" content="NO-CACHE">

Pero estoy buscando un método simple para desactivar la caché del navegador para todo un sitio web.

Author: Md. Alamin Mahamud, 2009-07-21

8 answers

HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
HttpContext.Current.Response.Cache.SetValidUntilExpires(false);
HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();

Todas las solicitudes se enrutan por defecto.aspx primero-así que suponiendo que sólo puede pop en el código detrás de allí.

 92
Author: Squiggs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-07 05:15:40

Cree una clase que hereda de IActionFilter.

public class NoCacheAttribute : 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);
    }
}

Luego coloque los atributos donde sea necesario...

[NoCache]
[HandleError]
public class AccountController : Controller
{
    [NoCache]
    [Authorize]
    public ActionResult ChangePassword()
    {
        return View();
    }
}
 365
Author: JKG,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-10 16:37:57

En lugar de rodar su propia, simplemente utilice lo que se proporciona para usted.

Como se mencionó anteriormente, no deshabilite el almacenamiento en caché para todo. Por ejemplo, los scripts de jQuery utilizados en gran medida en ASP.NET MVC debe almacenarse en caché. En realidad, lo ideal sería que usaras un CDN para esos de todos modos, pero mi punto es que algún contenido debe almacenarse en caché.

Lo que encuentro que funciona mejor aquí en lugar de rociar el [OutputCache] por todas partes es usar una clase:

[System.Web.Mvc.OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public class NoCacheController  : Controller
{
}

Todos tus controladores desea deshabilitar el almacenamiento en caché para luego heredar de este controlador.

Si necesita anular los valores predeterminados en la clase NoCacheController, simplemente especifique la configuración de caché en su método de acción y la configuración de su método de acción tendrá prioridad.

[HttpGet]
[OutputCache(NoStore = true, Duration = 60, VaryByParam = "*")]
public ViewResult Index()
{
  ...
}
 132
Author: Adam Tuliper - MSFT,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-19 18:47:07

Es posible que desee deshabilitar el almacenamiento en caché del navegador para todas las páginas renderizadas por los controladores (es decir, páginas HTML), pero mantenga el almacenamiento en caché para recursos como scripts, hojas de estilo e imágenes. Si está utilizando la agrupación y minificación MVC4+, querrá mantener las duraciones de caché predeterminadas para scripts y hojas de estilo (duraciones muy largas, ya que la caché se invalida en función de un cambio a una URL única, no en función del tiempo).

En MVC4+, para deshabilitar el almacenamiento en caché del navegador a través de todos los controladores, pero retenerlo para cualquier cosa no servida por un controlador, añadir esto a FilterConfig.RegisterGlobalFilters:

filters.Add(new DisableCache());

Define DisableCache como sigue:

class DisableCache : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    }
}
 10
Author: Edward Brey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-23 14:56:41

Sé que esta respuesta no está 100% relacionada con la pregunta, pero podría ayudar a alguien.

Si desea desactivar la caché del navegador para el entero ASP.NET MVC Website , pero solo desea hacer esto TEMPORALMENTE, entonces es mejor desactivar la caché en su navegador.

Aquí hay una captura de pantalla en Chrome

 6
Author: Carlos Martinez T,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-19 18:49:46

Implementé todas las respuestas anteriores y todavía tenía una vista que no funcionaba correctamente.

Resultó que el nombre de la vista con la que estaba teniendo el problema se llamaba 'Reciente'. Al parecer, esto confundió el navegador Internet Explorer.

Después de cambiar el nombre de la vista (en el controlador) a un nombre diferente (elegí 'Recent5'), las soluciones anteriores comenzaron a funcionar.

 2
Author: DrHooverCraft,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-19 18:48:52

Puede probar el siguiente código en Global.archivo asax.

protected void Application_BeginRequest()
    {
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
        Response.Cache.SetNoStore();
    }
 0
Author: NidhinSPradeep,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-08 09:19:29

UI

<%@ OutPutCache Location="None"%>
<%
    Response.Buffer = true;
    Response.Expires = -1;
    Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
    Response.CacheControl = "no-cache";
%>

Antecedentes

Context.Response.Cache.SetCacheability(HttpCacheability.NoCache); 
Response.Expires = -1;          
Response.Cache.SetNoStore();
 -1
Author: Alpha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-19 18:50:16