CORS in .NET Core

前端 未结 10 1090
失恋的感觉
失恋的感觉 2020-12-04 23:30

I am trying to enable CORS in .NET Core in this way:

    public IConfigurationRoot Configuration { get; }

    public void ConfigureServices(IServiceCollecti         


        
10条回答
  •  悲&欢浪女
    2020-12-05 00:22

    I just fixed my problem with Cors in Core 3.1. I was following almost every example and documentation out there. Unfortunately nothing worked until I did .Build() for the builder inside the AddPolicy portion.

            services.AddCors(options => {
                options.AddPolicy(
                    name: OrginPolicyKey, 
                    builder => builder.WithOrigins("http://localhost:3000")
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .Build() // <--- This right here
                );
            });
    

    Also, other people were mentioning about calling the UseCors(OrginPolicyKey) before the rest of your routing and UseMvc stuff. That is correct and I saw that Putting UseCors after the route part broke it. Below is how mine is setup.

            app.UseCors(OrginPolicyKey); // <--- First
    
            // Then routing stuff..
            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints
                    .MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}"
                    );
            });
    

    Who knew a builder needs to be built ;D

提交回复
热议问题