'ASP.NET Core Web API CORS error on Firefox but okay on Chrome

I have a React and ASP.NET Core 2.2 SPA that has a CORS issue with Firefox but is okay in Chrome and Edge. I've created a little test rig that consists of the ASP.NET Core 2.2 Web API template with CORS enabled and a Create React App that uses fetch to call the web API.

Here's the ASP.NET Core Startup.cs with CORS enabled:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
    {
        builder.AllowAnyMethod().AllowAnyHeader().AllowCredentials().WithOrigins("http://localhost:3000");
    }));
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors("CorsPolicy");
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseMvc();
}

Here's the React page that requests the data:

const App: React.FC = () => {
  const [data, setData] = useState("loading ...")  
  useEffect(()=>{
    fetch("https://localhost:44335/api/values").then(res=>res.json()).then(body=>{
      setData(JSON.stringify(body));
    })
  },[]);
  return <p>{data}</p>
}

This works fine in Chrome and Edge but I get the following error in Firefox:

enter image description here

Am I enabling CORS correctly? or am I missing something else? Any help appreciated.



Solution 1:[1]

On FireFox, the protocols must match for CORS policy origins. If your WebAPI has app.UseHttpsRedirection(); configured and your react app is being served from non SSL, you will get a CORS block. So either:

  • Disable app.UseHttpsRedirection(); in dev/local environment
  • Host your dev/local react app with SSL
  • Turn of SSL in iis express for the WebAPI

Solution 2:[2]

Just to add another facet to this...

I had a case where Firefox would give me a CORS error when calling a specific controller, but would work fine on other controllers in the same WebAPI instance.

What I found was on the 'problem' controller, it was actually throwing an exception. The exception in this case it was a 'Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException'. When I fixed the problem, the CORS errors went away. Probably other server-level exceptions would cause the same thing.

Who knows why FF would interpret an exception as a CORS error...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 prison-mike
Solution 2 pathrider