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
Solution
In Visual Studio 2017, you can enable the Enable SSL property, by following the below steps.
- Right-click on your project and choose Properties from the context menu.
- 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.
- services.AddCors(options =>
- {
- options.AddPolicy("CORS", corsPolicyBuilder => corsPolicyBuilder.AllowAnyOrigin()
-
- .AllowAnyMethod()
-
- .AllowAnyHeader()
-
- .AllowCredentials());
-
- });
Then, under the Configure method, use the below code to apply the CORS policy.
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.
- [EnableCors("CORS")]
- public class DefaultController : Controller{}
Note
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.