CORS headers with dot net core 3
Setting up a blanket CORS for .net core 3 is pretty simple, figuring out how to test it took longer than I care to realize…
This will hopefully be a short and sweet post, just wanna put this out there as a reminder, and to help someone that may just not realize much about testing changes with CORS.
The Project
Let’s create a new .net core 3 API with the command:
1 |
|
Now let’s run it with dotnet run
and see what we’re working with:
CORS
CORS being ‘disabled’ by default is the safe thing to do, you don’t necessarily want any other website to be able to access your API on a user’s behalf, some nefarious deeds could potentially occur. You can read more about the background of CORS here. All that being said, here’s how to do a blanket allow all origins.
From the Startup.cs
page, which should currently look like this:
We’ll want to make a few updates.
In the void ConfigureServices(IServiceCollection services)
method, we’ll want to add a CORS policy:
1 |
|
and within public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
:
1 |
|
That’s all there is to it!
To test
Now to test our fancy new CORS header (here’s where I ended up having issues)… Let’s run our app again through dotnet run
and hit our weatherForecast endpoint with Postman:
Hmm. There’s no CORS header. This is actually expected (maybe for people that have worked more closely with HTTP headers). The CORS header is only present when needed - when the request is being done on behalf of another website, another origin.
We can update our postman get request to contain an “Origin” header which will make our request look like it’s coming from a website, at which point the CORS header will be present:
There are many options you can do with the CORS header, obviously you should not allow ALL origins as I did in my example code, unless that’s something you need. You can very easily restrict it to specific domains.
That’s it, CORS headers on your .net core 3 API, and how to confirm the header!
Full code (although not much) can be found:
https://github.com/Kritner-Blogs/dotnetcoreCors/releases/tag/v1
CORS headers with dot net core 3
https://blog.kritner.com/2019/10/05/CORS-headers-with-dotnetcore-3/