Use Cors based on an appSettings in .Net Core
Solution 1
In ConfigureServices method, define two policies namely CorsAllowAll
and CorsAllowSpecific
services.AddCors(options =>
{
options.AddPolicy("CorsAllowAll",
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
options.AddPolicy("CorsAllowSpecific",
p => p.WithHeaders("Content-Type","Accept","Auth-Token")
.WithMethods("POST","PUT","DELETE")
.SetPreflightMaxAge(new TimeSpan(1728000))
.AllowAnyOrigin()
.AllowCredentials()
);
});
The setting CorsAllowAll
value can be accessed from IConfiguration
in Startup.cs. Depending on its value, it is possible to set one of the defined policies globally in Configure
method, before calling app.UseMvc()
.
//Read value from appsettings
var corsAllowAll = Configuration["AppSettings:CorsAllowAll"] ?? "false";
app.UseCors(corsAllowAll == "true"? "CorsAllowAll" : "CorsAllowSpecific");
Solution 2
This method works great. WithOrigins accepts a string [] so you can just split an appsettings value by ;
or something else.
appsettings.json
{
"AllowedOrigins": "http://localhost:8080;http://localhost:3000"
}
startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ApplicationDbContext dbContext, IOptions<AppSettings> appSettings)
if (!String.IsNullOrEmpty(_appSettings.AllowedOrigins))
{
var origins = _appSettings.AllowedOrigins.Split(";");
app.UseCors(x => x
.WithOrigins(origins)
.AllowAnyMethod()
.AllowCredentials()
.AllowAnyHeader());
}
The main reason for this semi colon format is because it is similar to Application\Properties\launchSettings.json
...
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "api/values",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Application": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "api/values",
"applicationUrl": "http://localhost:5000;http://192.168.50.20:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
...
user007
Updated on June 04, 2022Comments
-
user007 almost 2 years
I am updating a .net 4.5.2 project to .Net core web api. Right now, the Cors is setup as below based on an appSetting value
CorsAllowAll
:if ((ConfigurationManager.AppSettings["CorsAllowAll"] ?? "false") == "true") { appBuilder.UseCors(CorsOptions.AllowAll); } else { ConfigureCors(appBuilder); } private void ConfigureCors(IAppBuilder appBuilder) { appBuilder.UseCors(new CorsOptions { PolicyProvider = new CorsPolicyProvider { PolicyResolver = context => { var policy = new CorsPolicy(); policy.Headers.Add("Content-Type"); policy.Headers.Add("Accept"); policy.Headers.Add("Auth-Token"); policy.Methods.Add("GET"); policy.Methods.Add("POST"); policy.Methods.Add("PUT"); policy.Methods.Add("DELETE"); policy.SupportsCredentials = true; policy.PreflightMaxAge = 1728000; policy.AllowAnyOrigin = true; return Task.FromResult(policy); } } }); }
How can I achieve the same in .net core? Unfortunately, I won't be knowing the URLs of each environment. But I do know that for Local, DEV and QA environments, the appSetting
CorsAllowAll
is true. But the UAT and PROD environments it would be false.UPDATE My appSettings.json is like below:
"AppSettings": { ... "CorsAllowAll": true ... }
-
user007 almost 6 yearsMy appSettings is not at the root level. It is buried inside the element "AppSettings". I edited the question to include that..
-
user007 almost 6 yearsAlso, my question was not on just how to get the appSettings value. But how the appBuilder.useCors can be used based on the appSetting value? I am unable to use the
ConfigureCors
method in .net core.. -
user007 almost 6 yearsPlease edit the answer and use
Configuration["AppSettings:CorsAllowAll"]
.AppSettings
.CorsAllowAll
is null always.. -
Yared almost 6 years@user007 Updated my answer, Thanks.
-
Tyrrrz almost 4 yearsYou can also just use an array as well:
json { "AllowedOrigins": ["http://localhost:8080", "http://localhost:3000"] }
-
Germán Martínez about 2 years@Tyrrrz boy did your comment send me on a wild goose chase. Turns out you can't just
Configuration.GetValue<string[]>("AllowedOrigins")
and you have to jump through some hoops to do it.