Cuando desarrollamos nuestras aplicaciones web , muchas veces nos encontramos con un problema con el cual no contabamos la cache del navegador del usuario.

Para solventar este problema en ASP MVC contamos con la posibilidad de utilizar ActionFilterAttribute , en este articulo os enseñare a evitar el cache mediante un CustomFilter en ASP MVC.

Primero de todo crearemos un CustomFilter:

  public class NoCacheFilter : ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext ActionContext)
        {

            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();

        }

    }

Como veis sobreescribimos la función OnActionExecuting que nos permite captura la llamada al action. En ella definimos la cache del Response de nuestra action en asp mvc.

<h6>Implementación del NoCacheFilter en nuestras actions</h6>

[NoCacheFilter()]
 public ActionResult Index()
 {
       return View();
  }

Como siempre para vuestra comodidad os dejo el código en pastebin

Edición: Añado la versión en VB gracias a FdoGonzález

Public Class NoCacheFilter
Inherits System.Web.Mvc.ActionFilterAttribute

Public Overrides Sub OnActionExecuting(ByVal ActionContext As System.Web.Mvc.ActionExecutingContext)
MyBase.OnActionExecuting(ActionContext)
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()
End Sub

End Class