1

I have enabled CORS by adding below to webconfig but it doesnt seems to work consistently:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>

If we add an "Origin" header in the request, it does show Access-Control-Allow-Origin:* headers in response. But if we don't add "Origin" header in the request, the server doesn't return Access-Control-Allow-Origin:* headers.

The issue is, I am using sw-toolbox to precache static resources. But if a resource such as javascript files is already in browser cache before service worker is activated, for example the file is directly referenced in the html page and browser has already downloaded and cached the file, it shows CORS error when service worker tries to precache that file.

Naveed Ahmed
  • 10,048
  • 12
  • 46
  • 85
  • You need to enable [CORS in your application](https://learn.microsoft.com/en-us/aspnet/core/security/cors#enabling-cors-with-middleware). The web.config is just for IIS – Tseng Jan 13 '18 at 18:23
  • I already have it enabled in app app.UseCors(builder => { builder.AllowAnyOrigin(); builder.AllowAnyHeader(); builder.AllowAnyMethod(); }); But it adds Access-Control-Allow-Origin:* header to response only if there is an "Origin" header in the request. – Naveed Ahmed Jan 13 '18 at 22:04
  • Not sure I understand your problem. You don't need CORS for loading a **javascript** that's embedded via ` – Tseng Jan 13 '18 at 22:13
  • I want server to always return Access-Control-Allow-Origin:* header. Even for javascript that's embedded via – Naveed Ahmed Jan 13 '18 at 23:29
  • If you do not want your application to apply CORS on your static files you have to put CORS **AFTER** `UseStaticFiles`. Then it will only be applied to everything thats called afterwars (like MVC/Routing/Action results). It doesn't matter what you set in IIS for that, because this only applies for content hosted by IIS. But everything in `wwwroot` **is not** served by IIS but by your application – Tseng Jan 13 '18 at 23:40
  • Alternatively you will have to **move** the resources outside of `wwwroot` and put it in some directory you map in IIS and setup IIS to look there for it. Then the web.config CORS header will be applied and if no file is found will pass it through to your application. ASP.NET Core is an application of its own, not hosted inside IIS anymore like it used to be the case with legacy ASP.NET – Tseng Jan 13 '18 at 23:42

0 Answers0