Web api netcore 在 appsettings.json 文件中设置 Cors

moh*_*asi 2 asp.net-core-webapi

我正在使用 webapi .netcore 项目。我想将所有交叉设置放在 appsettings.json 文件中。我该怎么做呢?

这是我的代码:

 app.UseCors(x => x.WithOrigins("http://localhost:4200")
    .AllowCredentials()
    .WithHeaders("content-type")
    .WithMethods("GET", "POST", "PUT", "DELETE"));
Run Code Online (Sandbox Code Playgroud)

Yiy*_*You 7

如果您想设置 CORS 设置appsettings.json并使用 中的设置startup.cs,可以按照以下代码操作:

这是我的appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "AllowedOrigins": "http://localhost:4200",
  "AllowedHeaders": "content-type",
  "AllowedMethods": "GET,POST,PUT,DELETE"
}
Run Code Online (Sandbox Code Playgroud)

这是我的部分代码startup.cs

app.UseCors(x => x.WithOrigins(Configuration.GetSection("AllowedOrigins").Value.Split(","))
                  .AllowCredentials().WithHeaders(Configuration.GetSection("AllowedHeaders").Value.Split(","))
                  .WithMethods(Configuration.GetSection("AllowedMethods").Value.Split(",")));

app.UseHttpsRedirection();
Run Code Online (Sandbox Code Playgroud)