asp.net-core-webapicontent-security-policy

Why do I get this error from my ASP.NET Core Web API when I attempt to fetch API endpoint?


Background

I've been writing & running ASP.NET Core Web APIs for a long while now but suddenly when I attempt to retrieve a simple endpoint using fetch (more below) I get the following error:

VM22:1 Refused to connect to 'http://localhost:5116/Weatherforecast' because it violates the following Content Security Policy directive:
"default-src 'none'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.

I've never seen this in the past.

Steps To Reproduce

You can generate a very basic ASP.NET Core 8 Web API by doing the following:

$ dotnet core new webapi -o testApi

That will include an endpoint that provides weather data. You can do a GET on it from the web browser like:

http://localhost:5116/weatherforecast

You'll see something like:

sample weather data

Open Up Console / Terminal

However, if you open up a browser console (F12 in most browsers) and attempt the following command, then you will get the error I'm now seeing:

   fetch ("http://localhost:5116/Weatherforecast")
      .then(response => response.json())
      .then(data => console.log(data));

What I've Tried

I asked Copilot and it told me to add the following code to my Program.cs file:

app.Use(async (context, next) =>
{
    context.Response.Headers.Add("Content-Security-Policy", "default-src 'self';");
    await next();
});

This doesn't resolve the error though.

Added CORS Default

I also added the following code:

builder.Services.AddCors(options => options.AddDefaultPolicy(builder =>
{
    builder.AllowAnyOrigin()
           .AllowAnyMethod()
           .AllowAnyHeader();
}));

app.UseCors();

CURL Works

Also, note that CURL does work to retrieve from the URL:

curl -X 'GET' \
  'http://localhost:5116/weatherforecast' \
  -H 'accept: application/json'

What Will Resolve This?

What do I set in my Web API so I can make these fetch calls again?


Solution

  • Oh, wow, I found the definitive answer and it is a bit painful.

    Here's a snapshot of the error occurring in my browser (MS Edge running on Ubuntu 24.04.1)

    error occurs with specific URL

    Take note of the URL: localhost:5095/weatherforecast

    Now, let's try the fetch command, but first let's load localhost:5095 (no weatherforecast in the url in the main browser window.

    success on fetch when main URL loaded

    Now the fetch command works with no problem. Oy! In the past, it was the opposite - you had to run fetch commands on the console after loading a successful URL in your browser.

    Initial URL Determines Success Or Not

    So, this is all due to the initial URL where you attempt to run your fetch commands.