Resolving "Access-Control-Allow-Origin Header Not Present" Error In Angular .NET Core API Calls

Angular 4 is great and comes loaded with many features. You might be wondering why Angular 3 was skipped. They made it this way to unify all Angular components with the Angular Router (already developed up to version 3) which had to be upgraded to v4. So, Angular 4 was the chosen name to mean the entire Angular Framework.

Okay with that interesting information, let me come straight to the topic. Once we start working with Angular applications we will run into issues while calling our API’s from an Angular application using HTTP service of the Angular framework. The reason for this issue is in Angular -- every API call is an AJAX jQuery call, you may not face this issue with the API calls from pure C# code.

When you get this kind of issue, the hit goes to API Server and while returning the response, it was not able to send the result without the proper header.

Here is what you will encounter.

No 'Access-Control-Allow-Origin' header is present on the requested resource


In Visual Studio 2017, you can enable the Enable SSL property, by following the below steps.

  1. Right-click on your project and choose Properties from the context menu.
  2. Go to Debug tab, under Web Server settings which will look like below.


Make sure the Enable SSL property is checked.

You must set up CORS policy in your API. It is a three-step process as below.

  • Register CORS functionality
  • Configure CORS options
  • Apply the functionality

Open your .NET Core project and go to Startup.cs file where we are going to cover the above three steps.

Place the below code under ConfigureServices method to register and configure the CORS policy.

  1. services.AddCors(options =>  
  2. {  
  3.     options.AddPolicy("CORS", corsPolicyBuilder => corsPolicyBuilder.AllowAnyOrigin()  
  4.         // Apply CORS policy for any type of origin  
  5.         .AllowAnyMethod()  
  6.         // Apply CORS policy for any type of http methods  
  7.         .AllowAnyHeader()  
  8.         // Apply CORS policy for any headers  
  9.         .AllowCredentials());  
  10.     // Apply CORS policy for all users  
  11. });  

Then, under the Configure method, use the below code to apply the CORS policy.

  1. app.UseCors("CORS");  

If you want to apply CORS policy only for specific controllers, you can achieve that by removing the above code from Configure method and add it in the controller like below.

  1. [EnableCors("CORS")]  
  2. public class DefaultController : Controller{}  

In the three-code section, you should specify your CORS policy name and it must be the same in all three places.

You need to include namespace using Microsoft.AspNetCore.Cors; in order to access CORS features.

Please let me know if this has helped you. I would be happy if it did. Feel free to reach out to me if you need any specific assistance. I will try to help you out.

Similar Articles