MVC Back button issue

前端 未结 2 423
情话喂你
情话喂你 2021-01-03 16:57

I have an action method that I need to execute when the back button is clicked. I\'ve done this before by disabling the cache in my action method (Response.Cache.SetCacheabi

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-03 17:38

    Try the following, works great for me:

    public class NoCacheAttribute : ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            var response = filterContext.HttpContext.Response;
            response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
            response.Cache.SetValidUntilExpires(false);
            response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            response.Cache.SetCacheability(HttpCacheability.NoCache);
            response.Cache.SetNoStore();
        }
    }
    
    public class HomeController : Controller
    {
        [NoCache]
        public ActionResult Index()
        {
            // When we went to Foo and hit the Back button this action will be executed
            // If you remove the [NoCache] attribute this will no longer be the case
            return Content(@"Go to foo
    " + DateTime.Now.ToLongTimeString() + @"
    ", "text/html"); } public ActionResult Foo() { return Content(@"Go back to index", "text/html"); } }

提交回复
热议问题