visual-studiogoogle-chromecachingblazor

How to Stop Chrome Caching During Visual Studio Blazor Wasm App Debugging


I am using a small Blazor Wasm app to learn web programming. In particular, Visual Studio Community 2019 v16.6.2 with AspNetCore v3.2.0 and Chrome v83.0.4103.116. There are times when changes I make to my code (JavaScript and Blazor) aren't applied when I run the debugger, unless I do a Hard Refresh. I have set 'Disable cache' in the Network portion of the Chrome DevTools, but it doesn't remain set between debugging sessions. Having to do a Hard Refresh each time I debug just in case is of course a big pain. Any idea what I can do to prevent caching under these circumstances?


Solution

  • Short answer

    At the beginning of your index.html file, before any Blazor initialization, write a Javascript method call that clear the Blazor cache:

    <script type="text/javascript">
        caches.delete("blazor-resources-/").then(function (e) {
            console.log("'blazor-resources-/' cache deleted");
        });
    </script>
    

    By doing this, the Cache Storage will be cleared at each page load, just before the Blazor initialization.

    Full answer

    I think it is better to control the behavior of this depending the context. For a basic if in Debug or Release configuration, assuming that you are hosting your Blazor WASM application on ASP.NET Core, here are the steps:

    @page "/"
    @{
        Layout = ""; //Force no Layout
    
        bool clearCache = false;
    
    #if DEBUG
        clearCache = true;
    #endif
    }
    @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
    <!DOCTYPE html>
    <html>
    
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
        <title>MyProject</title>
        <base href="/" />
        <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
        <link href="css/app.css" rel="stylesheet" />
        <link href="Beeworking.Client.styles.css" rel="stylesheet" />
    </head>
    
    <body>
        <div id="app">Loading...</div>
    
        <div id="blazor-error-ui">
            An unhandled error has occurred.
            <a href="" class="reload">Reload</a>
            <a class="dismiss">🗙</a>
        </div>
        @if (clearCache)
        {
            <script type="text/javascript">
                caches.delete("blazor-resources-/").then(function (e) {
                    console.log("'blazor-resources-/' cache deleted");
                });
            </script>
        }
        <script src="_content/Microsoft.AspNetCore.Components.WebAssembly.Authentication/AuthenticationService.js"></script>
        <script src="_framework/blazor.webassembly.js"></script>
    </body>
    
    </html>