The same-origin policy is a standard security mechanism in web browsers that allows communications between two URLs only if they share the same origin, meaning the same protocol, port, and host. For example, a client or script at http://localhost:6000 will not be able to access a server application at http://localhost:5080 because these two URLs have different port addresses. Security restrictions in your web browser will not allow requests to a server application in another domain.
Here is where CORS (Cross-Origin Resource Sharing) comes to the rescue. CORS is a W3C standard that allows you to get around the default same-origin policy adopted by the browsers. In short, you can use CORS to allow some cross-origin requests while preventing others. In this article we’ll examine how CORS can be enabled and configured in ASP.Net Core.
Create an ASP.Net Core Web API project in Visual Studio 2017
First off, let’s create an ASP.Net Core Web API project in Visual Studio. If Visual Studio 2017 is up and running in your system, follow the steps outlined below to create an ASP.Net Core Web API project.
- Launch the Visual Studio 2017 IDE.
- Click on File > New > Project.
- Select “ASP.Net Core Web Application (.Net Core)” from the list of templates displayed.
- Specify a name for the project.
- Click OK to save the project.
- A new window “New .Net Core Web Application…” will be displayed.
- Select “.Net Core” as the runtime and ASP.NET Core 2.1 (or later) from the drop-down list at the top.
- Select “API” as the project template.
- Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked. We won’t be using Docker or HTTPS here.
- Ensure that “No Authentication” is selected as we won’t be using authentication either.