• Stars
    star
    342
  • Rank 123,697 (Top 3 %)
  • Language
    C#
  • License
    Other
  • Created about 7 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

ASP.NET Core Progressive Web Apps

Build status NuGet

A Progressive Web App (PWA) is a set of technologies that can be applied to any type of website and web application, and it consist of 3 components:

  1. Any website served over HTTPS
  2. A Web App Manifest (simple JSON file)
  3. A Service Worker JavaScript file

This components makes Web App Manifest a natural and integrated part of any ASP.NET Core web application and it comes with pre-built service workers so you don't have to write your own.

PWA install prompt

Building Progressive Web Apps have never been easier!

Install

To add the PWA service to your ASP.NET Core 2.0 application, simply add the NuGet package WebEssentials.AspNetCore.PWA.

Either do that through Visual Studio's NuGet Package Manager or the command line like this:

dotnet add package WebEssentials.AspNetCore.PWA

Getting started

You need to do a few things to turn your website into a PWA:

  1. Add two image icons to your project (192x192 and 512x512)
  2. Add a manifest.json file in the root of the wwwroot folder
  3. Register a service in Startup.cs
  4. Make sure it works

Step 1 - Icons

Get as many icons in various sizes as you want, but you MUST have both a 192x192 and a 512x512 size icon. Use PNG or JPEG.

Place the icons somewhere in the wwwroot folder.

Listing the size in the file names makes them easy to identify. Example: wwwroot/img/icon192x192.png Consider using Real Favicon Generator to generate images for different platforms and sizes.

Step 2 - manifest JSON file

Add the file wwwroot/manifest.json to your project and fill it in. It could look like this:

{
  "name": "Awesome Application",
  "short_name": "Awesome",
  "description": "The most awesome application in the world",
  "icons": [
    {
      "src": "/img/icon192x192.png",
      "sizes": "192x192"
    },
    {
      "src": "/img/icon512x512.png",
      "sizes": "512x512"
    }
  ],
  "display": "standalone",
  "start_url": "/"
}

Read more about the various properties in the W3C specificiation.

Now your file structure will look something like this:

Solution Explorer

Step 3 - register the service

Inside the ConfigureServices method in Startup.cs, add a call to services.AddProgressiveWebApp() like so:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddProgressiveWebApp();
}

A WebManifest object is now available in the Dependency Injection system in ASP.NET Core that allows you to access the contents of the manifest.json file through the strongly typed object.

You are now done converting your website into a PWA!

Step 4 - verify it works

If you've followed steps 1-3 then it's time to run your app in the browser and test that it is in fact a PWA. Here's how to verify it works:

Turn off JavaScript debugging in Visual Studio for the service worker to successfully register or follow this workaround.

Turn off JavaScript debugging from Tools > Options:

Debugger options

Launch the app in the Chrome browser.

View source and ensure the following element is present in <head>:

<link rel="manifest" href="/manifest.webmanifest" />

The file name is manifest.webmanifest and not manifest.json because this component is handling the request instead of serving manifest.json directly as a static file.

If you filled in the property theme_color in manifest.json then you'll also see this meta tag:

<meta name="theme-color" content="#ffffff" />

Just before the </body> end tag you'll see a script tag registering the service worker:

<script>'serviceWorker'in navigator&&navigator.serviceWorker.register('/serviceworker')</script>

Open the Chrome developer tools (F12) and navigate to the Application tab and select Service Workers. It should look somehting like this:

Chrome Dev Tools Application

If you see a service worker listed, then it was registered successfully. You may have to refresh the page in the browser to see it.

Pro tip: Make sure to check the checkbox name Update on reload for a better development time experience.

Clicking Manifest should show something like this:

Chrome Dev Tools Manifest

If you see both the service worker and the manifest information then it's all working and you have now successfully converted your site to a PWA!

Customize

You can customize various settings related to both the service worker and the Web App Manifest by passing in a PwaOptions object.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddProgressiveWebApp(new PwaOptions
    {
        RoutesToPreCache = "/, /contact.html, data.json",
        Strategy = ServiceWorkerStrategy.CacheFirst
    });
}

The same options can be set through the ASP.NET Core configuration system in appsettings.json:

{
  "pwa": {
    "registerWebmanifest":  true,
    "routesToPreCache": "/, /contact.html, data.json",
    "strategy": "cacheFirst"
  }
}

This means you can have settings specific to each of your environments (development, staging, production, etc.) by using various appsettings.<environment>.json files or by using environment variables.

If you use Visual Studio then you should get full Intellisense inside the pwa object in appsettings.json.

Customizing the Web App Manifest

You can use the Web App Manifest alone without the service worker by calling services.AddWebAppManifest() instead of services.AddProgressiveWebApp().

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddWebAppManifest();
}

By default it looks for a file named manifest.json in the wwwroot folder, but you can change the file name to whatever you like - just make sure it is located in the root of the wwwroot folder.

If you name it manifest.webmanifest then you are bypassing the middleware that handles the serving of the file and instead using the Static File middleware like it was any other static file. This can be desired for certain cases, but if you're in doubt then don't name it manifest.webmanifest.

Customizing the service worker

You can use the service worker alone without the Web App Manifest by calling services.AddServiceWorker() instead of services.AddProgressiveWebApp().

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddServiceWorker();
}

Configure the service worker

The options can be configured either in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddServiceWorker(new PwaOptions
    {
        CacheId = "v3",
        RoutesToPreCache = "foo.css, bar.js"
    });
}

...or in appsettings.json:

{
  "pwa": {
    "cacheId": "v1.0",
    "routesToPreCache": "foo.css, bar.js"
  }
}

Caching strategies

Specify which caching strategy you want to use if you want a different one than the default (CacheFirstSafe):

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddServiceWorker(new PwaOptions
    {
        Strategy = ServiceWorkerStrategy.CacheFirst
    });
}

...or in appsettings.json:

{
  "serviceworker": {
    "strategy": "cacheFirst"
  }
}

The options are:

CacheFirst

This strategy will add all requested resources to the service worker cache and serve it from the cache every time. If the cache doesn't have the requested resource it will fall back to the network and if that succeeds it will put the response in the cache.

CacheFirstSafe (default)

This strategy, like CacheFirst, will add all requested resources to the service worker cache. Unlike CacheFirst, it has special handling for HTML files and fingerprinted resources (resources with a v querystring parameter such as site.css?v=8udsfsaufd09sud0809sd_ds).

It will always attempt the network for HTML files (content type text/html) and fall back to the cache when the user is offline. That way the user always gets the latest from the live Internet when online.

For fingerprinted resources (the ones with a v querystring parameter) it will always try the cache first and fall back to the network.

CacheFingerprinted

This strategy only adds fingerprinted resources (resources with a v querystring parameter such as `site.css?v=8udsfsaufd09sud0809sd_ds) to the cache.

It will always try the cache for fingerprinted resources, then fall back to the network. For all other resources, it will use the network.

This strategy is useful for scenarios in which you don't wish to cache certain resources -- large video or audio files, for example -- but still wish to cache the app core assets (HTML, CSS, JS).

Minimal

The minimal strategy does nothing and is good for when you only want a service worker in order for browsers to suggest installing your Progressive Web App. For this to work, you need to add a web manifest file.

NetworkFirst

This strategy will always try the network first for all resources and then fall back to the cache when offline. When the network call succeeds, it will put the response in the cache.

This strategy is completely safe to use and is primarily useful for offline-only scenarios since it isn't giving any performance benefits.

CustomStrategy

This strategy will allow the user to specify their own implementation as a Javascript(.js) file. By default the app will search for a file named customserviceworker.js in the wwwroot folder.
A filename may be explicitly set by providing it as an option when registering the service in the Startup.cs or appsettings.json file.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddProgressiveWebApp(new PwaOptions { RegisterServiceWorker = true, Strategy = ServiceWorkerStrategy.CustomStrategy, CustomServiceWorkerStrategyFileName = "myCustomServiceworkerStrategy.js"});
        }

When creating the customserviceworker.js by providing {version}, {routes}, {ignoreRoutes} and {offlineRoute} values within the javascript file string, interpolation will be used to replace these values with option values as set in the Startup.cs or appsettings.json file.

(function () {
    //Insert Your Service Worker In place of this one!

    // Update 'version' if you need to refresh the cache
    var version = '{version}';
    var offlineUrl = "{offlineRoute}";
    var routes = "{routes}";
    var routesToIgnore = "{ignoreRoutes}";
});

.Net Core Application hosted as Virtual Directory

You can now specify a specific BaseURL if you plan to host your application as a Virtual Directory in IIS:

private const string _baseURL = "/PWAApp";

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddServiceWorker(new PwaOptions
    {
        BaseRoute = _baseURL;
        Strategy = ServiceWorkerStrategy.CacheFirst
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    //...
    app.UsePathBase(_baseURL);
    //...
}

...or in appsettings.json:

{
  "serviceworker": {
    "baseRoute": "/PWAApp",
    "strategy": "cacheFirst"
  }
}

Make sure to update your wwwroot/manifest.json file:

{
  "name": "Awesome Application",
  "short_name": "Awesome",
  "description": "The most awesome application in the world",
  "icons": [
    {
      "src": "/PWAApp/img/icon192x192.png",
      "sizes": "192x192"
    },
    {
      "src": "/PWAApp/img/icon512x512.png",
      "sizes": "512x512"
    }
  ],
  "display": "standalone",
  "start_url": "/PWAApp/"
}

License

Apache 2.0

More Repositories

1

Miniblog.Core

An ASP.NET Core blogging engine
JavaScript
1,466
star
2

WebEssentials2013

Visual Studio extension
C#
949
star
3

MiniBlog

A minimal blog engine using Razor Web Pages
C#
915
star
4

BundlerMinifier

Visual Studio extension
C#
616
star
5

ShortcutExporter

Visual Studio extension
C#
481
star
6

WebCompiler

Visual Studio extension for compiling LESS and Sass files
C#
448
star
7

MarkdownEditor

A Visual Studio extension
C#
397
star
8

WebEssentials2015

A Visual Studio extension for web developers
C#
302
star
9

AddAnyFile

A Visual Studio extension
C#
256
star
10

Tweakster

A Visual Studio extension
C#
241
star
11

PhotoGallery

ASP.NET Core Photo Gallery
C#
172
star
12

MarkdownEditor2022

A Visual Studio extension
C#
168
star
13

OpenCommandLine

A Visual Studio extension
C#
158
star
14

ExtensibilityTools

Tools for writing Visual Studio extensions
C#
153
star
15

JavaScriptPrettier

A Visual Studio extension
C#
151
star
16

RainbowBraces

A Visual Studio extension
C#
132
star
17

EditorConfigLanguage

A Visual Studio extension
C#
129
star
18

FileDiffer

A Visual Studio extension
C#
128
star
19

TrailingWhitespace

Display trailing whitespace in any VS editor
C#
118
star
20

PrivateGalleryCreator

Create private extension galleries for Visual Studio
C#
118
star
21

FileNesting

Nest files in Solution Explorer
C#
117
star
22

FileIcons

A Visual Studio extension
C#
115
star
23

WebEssentials2012

C#
96
star
24

NpmTaskRunner

Visual Studio extension
C#
88
star
25

TypeScriptDefinitionGenerator

A Visual Studio extension
C#
85
star
26

SolutionColors

A Visual Studio extension
C#
76
star
27

ZenCodingVS

A Visual Studio extension
C#
70
star
28

ExtensionPackTools

A Visual Studio extension
C#
67
star
29

MarkSite

A markdown powered CMS written in ASP.NET
C#
66
star
30

TextmateBundleInstaller

A Visual Studio extension
C#
65
star
31

RestClientVS

C#
65
star
32

ShowTheShortcut

A Visual Studio extension
C#
65
star
33

PackageInstaller

A Visual Studio extension
C#
64
star
34

CodeCleanupOnSave

C#
62
star
35

VuePack

C#
61
star
36

OpenInVsCode

A Visual Studio extension
C#
61
star
37

WebAnalyzer

A Visual Studio extension
C#
55
star
38

WebEssentials.AspNetCore.OutputCaching

C#
53
star
39

CommentRemover

A Visual Studio extension
C#
51
star
40

WebEssentials.AspNetCore.CdnTagHelpers

A CDN helper for ASP.NET Core
C#
49
star
41

WebEssentials2019

C#
49
star
42

ImageOptimizerWebJob

C#
47
star
43

DialToolsForVS

A Visual Studio extension
C#
47
star
44

ReverseProxyCDN

C#
42
star
45

CommandTaskRunner

A Visual Studio extension
C#
42
star
46

JSON-Intellisense

NPM package Intellisense in package.json
C#
40
star
47

WebPackTaskRunner

A Visual Studio extension
C#
40
star
48

VuePack2017

A Visual Studio extension
C#
38
star
49

AspNetCoreTemplatePack

C#
38
star
50

SolutionExtensions

A Visual Studio extension
C#
36
star
51

FeedCollector

A simple website for aggregating RSS/Atom feeds
C#
36
star
52

WebAccessibilityChecker

A Visual Studio extension
C#
34
star
53

VsixGallery

The Open VSIX Gallery
C#
34
star
54

ClearComponentCache

A Visual Studio extension
C#
33
star
55

Surrounder

A Visual Studio extension
C#
33
star
56

PrettyPaste

Fixes the added blank lines when copying and pasting from IE
C#
32
star
57

ImageSprites

A Visual Studio extension
C#
32
star
58

Editorsk

A Visual Studio extension
C#
30
star
59

JavaScriptSnippetPack

A Visual Studio extension
Vim Snippet
30
star
60

CloseAllTabs

A Visual Studio extension
C#
30
star
61

WorkspaceFiles

C#
30
star
62

IgnoreFiles

A Visual Studio extension
C#
29
star
63

DarkTheme2019

C#
29
star
64

zencoding

Provides hybrid ZenCoding for Web Essentials
C#
29
star
65

CommandTableInfo

A Visual Studio extension
C#
29
star
66

Madskristensen.VisualStudio.SDK

Visual Studio SDK meta packages
29
star
67

ImagePreview

C#
28
star
68

ExtensionGallery

A Visual Studio extension gallery
C#
28
star
69

Packman

A client-side package manager
C#
28
star
70

KnownMonikersExplorer

A Visual Studio extension
C#
28
star
71

SvgViewer

Shows the rendered image of .svg files
C#
27
star
72

SqlFormatter

C#
27
star
73

TemplateCreator

A Visual Studio extension
C#
27
star
74

BasicEssentials

26
star
75

DeveloperNews

C#
26
star
76

BrowserReloadOnSave

A Visual Studio extension
C#
26
star
77

StaticWebHelper

Perf optimize static websites hosted on IIS
C#
25
star
78

MIDL

A Visual Studio extension
C#
24
star
79

Community.VisualStudio.Toolkit

A community toolkit for writing Visual Studio extensions
C#
24
star
80

vswebessentials.com

The official website of Web Essentials for Visual Studio
C#
23
star
81

ExtensionUpdater

Visual Studio extension for auto updating extensions
C#
23
star
82

CssTools

A Visual Studio extension
C#
22
star
83

ExtensionScripts

PowerShell
22
star
84

InsertGuid

A Visual Studio extension
C#
22
star
85

CopyNice

A Visual Studio extension
C#
22
star
86

ErrorHighlighter

Visual Studio extension
C#
21
star
87

EditorColorPreview

C#
21
star
88

JsonSchemaGenerator

A Visual Studio extension
C#
20
star
89

SpaTemplatePack

A Visual Studio extension
C#
20
star
90

VsctIntellisense

Intellisense for VSCT files
C#
20
star
91

Madskristensen.VisualStudio.SDK.HelpersOLD

C#
19
star
92

PkgdefLanguage

A Visual Studio extension
C#
19
star
93

JavaScriptRegions

A Visual Studio extension
C#
19
star
94

OptionsSample

A Visual Studio extension sample
C#
19
star
95

GitHubThemes

C#
18
star
96

WebEssentialsChrome

A browser extension
JavaScript
18
star
97

OutputWindowFilter

C#
17
star
98

MiniBlogFormatter

C#
17
star
99

ShowKeybindings

A Visual Studio extension
HTML
17
star
100

GitPull

Easy way to "git pull" in Visual Studio
C#
16
star