5

I implementing ocelot in my new project, i create the integration of my services in one point with ocelot but when i try to post, put, path or delete to a resource in my api gateway, the browser show me the message

Failed to load http://localhost:8080/api/prospects: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8888' is therefore not allowed access. The response had HTTP status code 404.

I try to configure cors in gateway installing and implementing the package Microsoft.AspNetCore.Cors

  public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();
        services.AddOcelot(Configuration)
            .AddCacheManager(x =>
            {
                x.WithMicrosoftLogging(log =>
                {
                    log.AddConsole(Microsoft.Extensions.Logging.LogLevel.Debug);
                })
                .WithDictionaryHandle();
            }); ;
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, Microsoft.Extensions.Logging.ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        app.UseCors(
            options => options.WithOrigins("http://localhost:8888").AllowAnyMethod()
        );
        app.UseOcelot().Wait();
    }
rawel
  • 2,923
  • 21
  • 33
Alejandro Mora
  • 157
  • 3
  • 16

1 Answers1

4

This question doesn't concern to Ocelot, CORS works as same for all .net core api

try first implement CORS for AnyOrigin like this

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
        });

        services.AddMvc();
        services.AddOcelot(Configuration);
    }

and in Configure method add this line app.UseCors("CorsPolicy");

so after that if CORS worked, instead of .AllowAnyOrigin() add .WithOrigins("yourdomain") and that it

for more information see: https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.2

Adam Bremen
  • 685
  • 1
  • 7
  • 18