Friday 8 March 2019

[Solved] Fix CORS Policy between Angular and .net Core Web API

Hi Readers,

Are you facing the following issue:

Access to XMLHttpRequest at 'http://localhost:5000/api/auth/login' 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.

Solution for the above problem is to enable CORS Policy in .NET Core WEB API project.

File: Startup.cs:

In Configure Method,
Add this line: app.UseCors(); on top of app.UseMvc();

In Configuration Services Method,

            services.AddCors(options =>
            {
                options.AddPolicy(builder =>
                {
                    builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials().Build();
                });
            });


In Client Side, Consider ClientApp is Angular Application
Inside Environments/environment.ts file add the following snippet

export const environment = {
production: false,
ApiBaseUrl : "http://localhost:5000/"
};


With the above codes, CORS policy issue is resolved and we process request and response without any issues.


Happy Coding:)

No comments:

Post a Comment