tony
tony

Reputation: 2392

Service Worker in Asp.Net MVC, scope

Does the scope of a service worker have to be root for an asp.net mvc application? It needs to see the controller, it will need scripts, etc. My concern is what happens on a very large application.

If using an Area, you can include scripts in the area so that's one way of narrowing it down, are there any best practices?

Upvotes: 4

Views: 3670

Answers (1)

joeshmoe301
joeshmoe301

Reputation: 1418

You can place the service worker file anywhere you want. Here's how I did it.

Let's assume you setup an area called "Customer". So your file structure would be "/Areas/Customer", "/Areas/Customer/Controllers", "/Areas/Customer/Models", "/Areas/Customer/Views", etc. Assuming you didn't change the routing, the url would be "https://www.somewebsite.com/customer". If you want to make the scope of your service worker "/customer", but not have the service worker javascript file in the root, you would do the following.

I'm going to make another assumption that you created a "scripts" folder in this location "/Areas/Customer/Scripts" to hold your server worker js file.

In the javascript file that registers your service worker, you would do something like this.

if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/areas/customer/scripts/serviceworker.js", { scope: "/customer" })
    .then(registration => {
        console.log("Service Worker registered properly.");
    })
    .catch(error => {
        console.log("Service Worker NOT registered properly.");
    });
}

If you run the site now, you will receive an error similar to this "The path of the provided scope ('/customer') is not under the max scope allowed ('/areas/customer/scripts/'). Adjust the scope, move the Service Worker script, or use the Service-Worker-Allowed HTTP header to allow the scope."

What you need to do is update your web.config file with the below text in order to send the Service-Worker-Allowed HTTP header. This goes in the "configuration" section of web.config.

  <location path="areas/customer/scripts/serviceworker.js">
    <system.webServer>
      <httpProtocol>
        <customHeaders>
          <add name="Service-Worker-Allowed" value="/customer" />
        </customHeaders>
      </httpProtocol>
    </system.webServer>
  </location>

This should now allow you to have your serviceworker.js file in a folder other than the root, but still keep the scope of the service worker to the correct area.

Upvotes: 2

Related Questions