A Simple CORS Example with a .NET 6 Web API Application and a .NET 6 Web Application

Download full source code.

CORS (Cross-Origin Resource Sharing) is one of those things that I need to work on from time to time. But it is so infrequent that I have to re-read and figure it out anew each time. So I’ve decided to write a blog post to my future self.

My usual scenario is -

  1. I’ve written a Web API application.
  2. Some web page on other web application needs to call my API with JavaScript.
  3. The developer of the web application comes to me saying they got a CORS error when calling my API.
  4. I say, “that has happened before, let me figure out what I did last time…”.
  5. Repeat steps 1 to 4 a couple of years later.

1. My Web API application

Create a simple Web API application with a controller that returns some JSON data. (dotnet new webapi --name ...)

Out of the box, this application will contain a WeatherForecastController that returns JSON when called.

Go into Properties/launchSettings.json, there will be a profile with the name of the application you created, change its ApplicationUrl to https://localhost:5001/.

Let’s leave the rest of the code as it is.

2. Some other web application needs to call my API with JavaScript

Create a Web Application (dotnet new webapp --name ...).

Open Pages/index.cshtml and replace with the following code -

@page

<div class="text-center">
    <h1>A very simple CORS demo</h1>
</div>
<input type="button" value="Get Weather Forecast" onclick="FetchRemote('https://localhost:5001','/weatherforecast', 'GET')"/>

<div>
    <span id='remoteResponse'></span>
</div>
<script src="~/js/site.js"></script>

This will be one of the ugliest pages you have ever made, but it’s about as good as I can manage.

Open the wwwroot/js/site.js file and add the following code -

function FetchRemote(remoteHost, path, httpMethod) {
    const remoteResponse = document.getElementById('remoteResponse');

    fetch(`${remoteHost}${path}`,
    {
        method: httpMethod,
    }).then(response => {
        if (response.ok) {
            response.text().then(text => {
                remoteResponse.innerText = text;
            });
        }
        else {
            remoteResponse.innerText = response.status;
        }
    })
    .catch(() => remoteResponse.innerText = 'An error occurred, might be CORS?! :) Press F12 to open the web debug tools');
}

Open Properties/launchSettings.json, there will be a profile with the name of the application you created, change the ApplicationUrl to https://localhost:8081/.

Your web application should now be able to call your API using JavaScript.

3. The CORS error

Start the Web API application and the Web Application. Open the developer tools in your browser and go to the Console tab (or the Network tab).

Click the button that says Get Weather Forecast and you will get a CORS error -

There, you have replicated the CORS error.

Now to fix it.

4. The fix

Here’s the simple thing to remember - the fix has to happen in the Web API application, it needs to say that it allows requests originating from the Web Application. No changes are needed in the Web Application.

In the Web API application, add the following code to the Program.cs file -

builder.Services.AddCors(options =>
{
options.AddPolicy("MyAllowedOrigins",
    policy =>
    {
        policy.WithOrigins("https://localhost:8081") // note the port is included 
            .AllowAnyHeader()
            .AllowAnyMethod();
    });
});

Then, add the following a little lower down in Program.cs -

var app = builder.Build(); // this will already be in the file
app.UseCors("MyAllowedOrigins");

Restart the Web API application and the Web Application.

Now when clicking the button on the Web Application, it will work.

Download full source code.

comments powered by Disqus

Related