Search code examples
cachingasp.net-corebrowserback-button

Browser back button does not execute the controller method


I am working in asp.net core. I am facing an issue which is when I am returning to last visited web page through the browser back button, my controller action method is not being executed.

When we press the back button, the browser fetches data from the cache. So, if we want to execute the controller action method, we need to prevent the browser from caching that page.

I googled a lot about this. Through this, I found a lot of solution based on the cache in ASP.NET MVC. Like, disabling cache.

I checked this site and tried also. https://learn.microsoft.com/en-us/aspnet/core/performance/caching/response?view=aspnetcore-2.2 . It's not working.

We are performing some actions based on the cookies. So disabling cache, should not clear this also.

Is there any another way in ASP.NET Core to execute the controller action method when press browser back button?

Thanks in advance.


Solution

  • You should be careful while using no-cache, because caching plays an important role in performance.

    If you want to set specific controller action with no-cache, you could do the following:

    1. configure CacheProfiles in Startup.cs
    services.AddMvc(options =>
    {
        options.CacheProfiles.Add("Never",
            new CacheProfile()
            {
                Location = ResponseCacheLocation.None,
                NoStore = true
            });
    }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    
    1. Usage
    [ResponseCache(CacheProfileName = "Never")]
    public IActionResult Index()
    {
        return View();
    }    
    

    If you insist in using no-cache for all requests, try middleware.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.Use(async (context, next) =>
        {
            context.Response.OnStarting(() =>
            {
                if (context.Response.Headers.ContainsKey("Cache-Control"))
                {
                    context.Response.Headers["Cache-Control"] = "no-cache,no-store";
                }
                else
                {
                    context.Response.Headers.Add("Cache-Control", "no-cache,no-store");
                }
                if (context.Response.Headers.ContainsKey("Pragma"))
                {
                    context.Response.Headers["Pragma"] = "no-cache";
                }
                else
                {
                    context.Response.Headers.Add("Pragma", "no-cache");
                }
                return Task.FromResult(0);
            });
            await next.Invoke();
        });
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }
    
        app.UseStaticFiles();
    
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }