Thursday, March 23, 2017

How to enable cors globally in asp.net web api core

Leave a Comment

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();         } 

2 Answers

Answers 1

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.

Answers 2

Refer this link of stackoverflow

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment