根据.Net Core中的appSettings使用Cors [英] Use Cors based on an appSettings in .Net Core
问题描述
我正在将.net 4.5.2项目更新为.Net核心Web API.现在,基于appSetting值CorsAllowAll
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);
}
}
});
}
如何在.net core中实现相同的目的?不幸的是,我不会知道每种环境的URL.但是我确实知道,对于本地,DEV和QA环境,appSetting CorsAllowAll
是正确的.但是在UAT和PROD环境中,它是错误的.
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.
更新 我的appSettings.json如下所示:
UPDATE My appSettings.json is like below:
"AppSettings": {
...
"CorsAllowAll": true
...
}
推荐答案
在ConfigureServices方法中,定义两个策略,即CorsAllowAll
和CorsAllowSpecific
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()
);
});
可以从Startup.cs中的IConfiguration
访问设置CorsAllowAll
的值.根据其值,可以在调用app.UseMvc()
之前在Configure
方法中全局设置已定义的策略之一.
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");
这篇关于根据.Net Core中的appSettings使用Cors的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!