Search code examples
asp.netcachingasp.net-mvc-5progressive-web-appsservice-worker

Is there any way to cache all files with service worker in ASP .NET MVC5?


I want to make my legacy ASP .NET MVC5 project to PWA so i'm setting service worker.
And i want Project file in /Views/Home/ directory be cached.

So I added cache list like this.

const CACHE_NAME = "cache";
const CACHE_LIST = [
    "/",
    "/Views/",
    "/Views/Home/",
    "/Views/Home/Project"
]

const addResourcesToCache = async (resources) => {
    const cache = await caches.open(CACHE_NAME);
    await cache.addAll(resources);};
}

self.addEventListener('install', (event) => {
    self.skipWaiting();
    event.waitUntil(
        addResourcesToCache(CACHE_LIST)
    );
});

But It didn't worked. It occurs error.

Uncaught (in promise) TypeError: Failed to execute 'addAll' on 'Cache': Request failed

I've tried Is there any way to cache all files of defined folder/path in service worker? but doesn't worked.

And I changed cache list like this and it worked.

(http://localhost:23402/subdomain1/subdomain2/subdomain3/ is url about Project file.)

const CACHE_LIST = [
    "/",
    "http://localhost:23402/subdomain1/subdomain2/subdomain3/"
]

But i have to cache all files in my legacy project so i can't register cache one by one like that.
I want to cache all files with file path not url.

How can i solve this problem?


Solution

  • Yes

    But your service worker and your server code (C#) are completely decoupled. So what you cached in your service worker has basically nothing to do with what is rendered from your website, or really how it is rendered.

    Think of the service worker as a web server that runs inside the browser.

    You can render HTML, etc from the service worker. You make HTTPS requests to get data (HTML, CSS, JS, images, JSON, videos). You can cache any response object, even create response objects in the service worker and cache them in the service worker cache. You can also cache raw data in IndexedDB (which I use a lot in my applications).

    This seems to be a common misconception of developers. The service worker is independent. It does not care if you use ASP.NET, JSP, WordPress or CGI bin for that matter. I personally use static HTML and API calls that return JSON in my applications now. No ASP.NET anymore :( Haven't for about 7 years now.