我使用Blazor Webassembly应用程序的默认项目模板创建了一个新项目,并已标识,托管了asp.net核心并选中了PWA选项。这使我们有了一个WASM blazor SPA应用程序,它具有一些基本的脱机PWA功能,以及一个服务器端的asp.net核心应用程序。
使用身份验证时,页面由服务器应用程序提供。因此,当应用程序离线运行时,无法访问它们。这是可以预料的,但是在这种情况下,默认404或浏览器呈现的“您没有互联网”页面的用户体验(开箱即用)很差。
我想清理此问题,以便向用户安全/优美地警告无法获取远程页面。我开始查看模板提供的service-worker.js,它已经包含处理“连接”和“身份” URL并确保从服务器端获取它们的代码。我尝试使用此处显示的方法添加到此内容-https://googlechrome.github.io/samples/service-worker/custom-offline-page/
async function onFetch(event) {
let cachedResponse = null;
var shouldServeIndexHtml = true;
console.info('Service worker: onFetch');
if (event.request.method === 'GET') {
// For all navigation requests, try to serve index.html from cache
// If you need some URLs to be server-rendered, edit the following check to exclude those URLs
shouldServeIndexHtml = event.request.mode === 'navigate'
&& !event.request.url.includes('/connect/')
&& !event.request.url.includes('/Identity/');
const request = shouldServeIndexHtml ? 'index.html' : event.request;
const cache = await caches.open(cacheName);
cachedResponse = await cache.match(request);
}
console.info('Service worker event.request.url: ' + event.request.url);
if (cachedResponse != null) {
console.info('Service worker we have cachedResponse: ' + cachedResponse.url);
return cachedResponse
} else {
console.info('Service worker cachedResponse is null, starting fetch ');
try {
const networkResponse = await fetch(event.request);
return networkResponse;
} catch (error) {
// catch is only triggered if an exception is thrown, which is likely
// due to a network error.
// If fetch() returns a valid HTTP response with a response code in
// the 4xx or 5xx range, the catch() will NOT be called.
console.log('Fetch failed; returning offline page instead.', error);
console.log('Fetch failed shouldServeIndexHtml ',shouldServeIndexHtml);
if (shouldServeIndexHtml == false) {
console.log('Fetch failed, attempting fallback');
const request = 'index.html';
const cache = await caches.open(cacheName);
cachedResponse = await cache.match(request);
if (cachedResponse != null) {
console.info('Service worker we have fallback cachedResponse: ' + cachedResponse.url);
return cachedResponse
} else {
console.info('Service worker fallback cachedResponse is null');
}
}
}
}
}
目前代码很粗糙,很抱歉!
此 几乎 有效。如果尝试将GET尝试访问服务器页面(以shouldServeIndexHtml = false标识),则现在将尝试通过try / catch进行获取。捕获然后触发,我尝试路由到“ index.html”,但这是所有问题的归宿。这以Blazor客户端路由器转到NotFound布局结束。
这使我认为这不是最好的方法,但是是否有其他人尝试使用服务工作者或其他方法来解决此问题?