.Net Core : Enable CORS in ASP.net Core WebAPI

.Net Core : Enable CORS in ASP.net Core WebAPI


Enable CORS in ASP.net Core WebAPI


In ConfigureServices method

  public void ConfigureServices(IServiceCollection services)
        { 
            services.AddCors(options => options.AddPolicy("ApiCorsPolicy", builder =>
            {
                builder.WithOrigins("http://localhost:4200").AllowAnyMethod().AllowAnyHeader();
            }));

            services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DotNetCoreDB")));
             
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

In Configure method

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            } 
            app.UseAuthentication();

            app.UseCors(
                options => options.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials()
            );
 
            app.UseMvc();
        }


Hope this will help you and save your time.

Enjoy !!!

:)

No comments:

Post a Comment