Luis Valencia
Luis Valencia

Reputation: 34038

How to enable CORS globally in ASP.NET web API core

I found this site:

https://learn.microsoft.com/en-us/aspnet/core/security/cors

However I am confused in how to enable it globally, because it seems there are 2 ways to do it, whats the difference between these 2 ways? or they do 2 different things?

public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //https://learn.microsoft.com/en-us/aspnet/core/security/cors
            services.AddCors(options =>
            {
                options.AddPolicy("AllowSpecificOrigin",
                    builder => builder.WithOrigins("http://example.com")
                                        .AllowAnyHeader()
                    );
            });

            services.Configure<MvcOptions>(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
            });

            // Add framework services.
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseCors("AllowSpecificOrigin");

            app.UseMvc();
        }

Upvotes: 6

Views: 897

Answers (1)

Shawn Wildermuth
Shawn Wildermuth

Reputation: 7468

The calls in the ConfigureServices just adds Cors services, not set it up (including creating hte policy). By adding the filter you're making it global, but I understand that the UseCors (in Configure) is the preferred way to add it globally. All that the Filter code does is force the attribute on all controllers, and the UseCors effectively does the same thing, just in a different part of the stack. I believe the UseCors will do it for more than just MVC calls which is why it's different.

Upvotes: 5

Related Questions