Access to xmlhttprequest at from origin has been blocked by cors policy in Angular 6

Mohan Perera picture Mohan Perera · Feb 6, 2019 · Viewed 15k times · Source

I'm using Asp.Net Core Boilerplate framework for my server side project. Angular 6 using for the client side project. Server side project working without any errors. (Showing Swagger API - and APIs are also working)

No any compile errors from Angular project. When run the angular project using Google chrome, (http://localhost:4200/) it showing following error message.

enter image description here

Browser console displays this :-

Access to XMLHttpRequest at 'http://server.projectName.lk//AbpUserConfiguration/GetAll' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

When click on the ''http://server.projectName.lk//AbpUserConfiguration/GetAll'' link, it opens in a another tab and showing below error,

enter image description here

Highly appreciate your ideas to solve this..

NOTE : No any previous questions gave me a solution.

This is the debug error log you receive for this issue

> The thread 0x54b0 has exited with code 0 (0x0).
> Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request
> starting HTTP/1.1 OPTIONS
> http://localhost:21021/AbpUserConfiguration/GetAll  0
> Microsoft.AspNetCore.Cors.Infrastructure.CorsService:Information: CORS
> policy execution failed.
> Microsoft.AspNetCore.Cors.Infrastructure.CorsService:Information:
> Request origin http://localhost:4200 does not have permission to
> access the resource.
> Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request
> finished in 311.689ms 204 
> Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information:
> Route matched with {action = "Index", controller = "Home", area = ""}.
> Executing action San.BA.Web.Host.Controllers.HomeController.Index
> (San.BA.Web.Host) The program '[21292] dotnet.exe' has exited with
> code -1 (0xffffffff).

startup.cs File

Answer

Charanjit Singh picture Charanjit Singh · Feb 7, 2019

Cross Origin Resource Sharing (CORS) is a W3C standard that allows a server to relax the same-origin policy. Using CORS, a server can explicitly allow some cross-origin requests while rejecting others. CORS is safer and more flexible than earlier techniques, such as JSONP. This topic shows how to enable CORS in an ASP.NET Core app.

This is happening due to the CORS Policy failed on the server side. As you need to either add the client url in appsettings.json file in host Project.

"App": { ...... "CorsOrigins": "http://localhost:4200" ...... }

For more information you can check the following URL:
https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.2