Reputation: 4124
I am trying to add multiple rul which should be whitelisted for CORS.
Problem is only single url work. My code is as following
public class StartupShutdownHandler
{
private static readonly log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private const string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public StartupShutdownHandler(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddMvc(options => { options.RespectBrowserAcceptHeader = true; }).AddXmlSerializerFormatters().AddXmlDataContractSerializerFormatters();
CorsRelatedPolicyAddition(services);
}
private void CorsRelatedPolicyAddition(IServiceCollection services)
{
/* var lstofCors = ConfigurationHandler.GetSection<List<string>>(StringConstants.AppSettingsKeys.CORSWhitelistedURL);
*/
var lstofCors = new List<string> {"url1", "url2"}
if (lstofCors != null && lstofCors.Count > 0 && lstofCors.Any(h => !string.IsNullOrWhiteSpace(h)))
{
services.AddCors(options =>
{
//https://stackoverflow.com/questions/43985620/asp-net-core-use-multiple-cors-policies
foreach (var entry in lstofCors.FindAll(h => !string.IsNullOrWhiteSpace(h)))
{
options.AddPolicy(MyAllowSpecificOrigins, builder => { builder.WithOrigins(entry); });
}
});
}
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime applicationLifetime)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(MyAllowSpecificOrigins);
// CheckAndEnableDetailLogs(app);
app.UseMvc();
}
}
Upvotes: 0
Views: 95
Reputation: 679
You are overriding the options for every entry in your array.
Just add the entries as an array of strings.
var lstofCors = new string[] {"url1", "url2"};
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins, builder => { builder.WithOrigins(lstofCors.ToArray()).AllowAnyMethod(); });
});
}
Edit: I have added AllowAnyMethod() as looks like only get method is working
Upvotes: 1