как разрешить CORS для метода POST и PUT с c# интерфейс reactJS - PullRequest
0 голосов
/ 27 мая 2020

ПРОБЛЕМА: в localhost все методы (GET, POST, PUT) работают нормально, но после развертывания на сервере я получил ошибку CORS POLICY BLOCKED. хотя на сервере метод GET работает нормально

C# с ядром ef после моего файла Startup.cs.

publi c class Startup {publi c Startup (конфигурация IConfiguration) {Configuration = конфигурация; }

    readonly string AllowLocalHostOrigins = "_allowLocalHostOrigins";

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {

        services.AddDbContextPool<venus_aestheticsContext>(options => options
           // replace with your connection string
           .UseMySql(Configuration["dbConnection:startup"],
               mysqlOptions =>
               {
                   mysqlOptions
                       .ServerVersion(new Version(8, 0, 18), ServerType.MySql);
               }));
        // services.AddScoped<IDataRepository<Token, long>, TokenManager>();
        // services.AddMvc();

        // Register the Swagger generator, defining 1 or more Swagger documents
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
        });

        services.AddControllers().AddNewtonsoftJson(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
        services.AddControllers();

        // enable cors
        services.AddCors(options =>
        {
            options.AddPolicy(AllowLocalHostOrigins,
                builder =>
                {
                    builder.WithOrigins("http://localhost:3000").AllowAnyHeader().AllowAnyMethod();
                    builder.WithOrigins("http://www.testing.com").AllowAnyHeader().AllowAnyMethod();
                });
        });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
        services.AddDistributedMemoryCache();
        services.AddSession(options =>
        {
            options.Cookie.HttpOnly = true;
            options.Cookie.IsEssential = true;
        });

        //     services.AddPaging();

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseOptions();
        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
        // specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            //c.RoutePrefix = string.Empty;

        });

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();
        app.UseSession();

        app.UseRouting();
        app.UseCors(AllowLocalHostOrigins);
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

1 Ответ

0 голосов
/ 27 мая 2020

Не могли бы вы заменить

app.UseCors(AllowLocalHostOrigins);

на

app.UseCors(builder => builder
   .AllowAnyOrigin()
   .AllowAnyMethod()
   .AllowAnyHeader()
   .AllowCredentials());
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...