Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I found this site:

https://docs.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://docs.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();
        }
like image 310
Luis Valencia Avatar asked Mar 14 '17 20:03

Luis Valencia


People also ask

How do I add a CORS policy to .NET core?

Enabling CORS in ASP.NET Core with Attributes We can use just the [EnableCors] attribute on top of the controller or the action, and it will implement a default CORS policy. Or we can use the [EnableCors("Policy name")] attribute, to apply a named CORS policy.


1 Answers

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.

like image 118
Shawn Wildermuth Avatar answered Oct 10 '22 21:10

Shawn Wildermuth