.NET Web API Error Access to XMLHttpRequest from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Updated on: September 21, 2019

When you are calling .NET Framework Web.API 2 OR .NET Core Web API from Angular 8 or any other Front end application and getting following error, then following fix with resolve your issue:

Access to XMLHttpRequest at 'http://localhost:51453/api/Values?userName=test&password=test' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

As from above error, it is clear that once Web.API is cross domain accessible, then it will add "Access-Control-Allow-Origin: *" in the Security header in the response of Web.API. If it is not exists in the response header, then it is clear that CORS is not implemented for Web.API project, then we will have to implement it by following steps given below:

Step 1: Create .NET Framework Web API OR .NET Core Web API project

Step 2: Right click on the project and click on "Manage NuGet Packages..." option

Step 3: Click on the Browse option on NuGet Package Manager window

Step 4: Click on Search textbox and search for "cors"

Step 5: Select the appropriate NuGet package, if you are in .Net Framework Web API project, then select "Microsoft.AspNet.WebApi.Cors" or if you are in .NET Core Web API project, then select "Microsoft.AspNetCore.Cors" NuGet package and click on Install button from right section of NuGet Package Manager.

Step 6: Rebuild the solution to check for any errors

Step 7: If you are using .Net Framework Web API project, add following changes

1. Add following code in the beginning of Register() method of WebApiConfig.cs file in App_Start folder:

config.EnableCors();

2. Open the controller which you want to access outside the domain and add this following attribute at the controller level:

[EnableCors(origins: "*", headers: "*", methods: "*")]

If you are using .NET Core Web API project, add following changes:

1. Add following code after services.AddMvc() line in the ConfigureServices() method of Startup.cs file:

services.AddCors(c =>
            {
                c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
            });

2. Add following code after app.UseMvc() line in the Configure() method of Startup.cs file:

app.UseCors(options => options.AllowAnyOrigin());

3. Open the controller which you want to access outside the domain and add this following attribute at the controller level:

[EnableCors("AllowOrigin")]

Step 8: Once you done with these changes, publish your Web API to access it from other domains

Step 9: Once you complete all the above steps, your CORS error should get solved.