CORS on .NET Core 2 with Web API

How to enable CORS in ASP.net Core WebAPI

Install-Package Microsoft.AspNetCore.Cors

public void ConfigureServices(IServiceCollection services)
{
  services.AddCors();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IConfiguration config)
{
  //  ...
  app.UseCors(options =>
      options.WithOrigins("http://example.com")
          .AllowAnyMethod()
          .AllowAnyHeader()
          .AllowCredentials();
  );
  app.UseCors(builder => {
      var allowedOrigins = config.GetSection("AllowedOrigins").GetChildren().ToArray().Select(c => c.Value).ToArray();
      logger.LogInformation("Allowed Origins: {0}", string.Join(", ", allowedOrigins));
      builder.WithOrigins(allowedOrigins).AllowAnyMethod();
  });
  //    ...
}

References

  1. original MSDN instructions
  2. based on StackOverflow discussion
  3. obsolete link contains instructions for older version of Web API (Web API 1). It does not work on VS 2017 project with .NET Core 2.
  4. CORS in .NET Core 2.0 “No Access-Control-Allow-Origin header is present on the requested resource.”