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();
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With