【发布时间】:2018-04-18 22:14:32
【问题描述】:
我正在开发一个由多个项目组成的 .NET Core 2.1.103 WebAPI 应用程序。每个项目都需要有自己的 appsettings.json 文件。每个项目都位于主“解决方案”文件夹中的自己的子目录中。这是目录结构的简化版本,其中包含我的问题的相关目录:
c:\code\my_big_solution
c:\code\my_big_solution\project1
c:\code\my_big_solution\project1\bin\Debug
c:\code\my_big_solution\project2
c:\code\my_big_solution\project2\bin\Debug
c:\code\my_big_solution\project3
c:\code\my_big_solution\project3\bin\Debug
我很难弄清楚每个 appsettings.json 文件必须放在哪里以及如何读取它们。我假设通过阅读其他帖子,我应该自动将每个项目的 appsettings.json 文件复制到其关联的 bin\Debug 目录。如果是这种情况,我不确定如何使用 Startup 构造函数。我的理解是,这是 .NET Core 2.0 从 appsettings.json 文件中读取值的方式:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
string myString = Configuration["blah:blah:blah"];
configuration 似乎是从 c:\code\my_big_solution 获取其 appsettings.json 文件,而不是从 c:\code\my_big_solution\project1\bin\Debug 或我想从中提取的任何项目的 Debug 目录。
我不知道如何从所需的目录中提取,除了使用 .NET Core 1.x 的方式,这是通过更改构造函数,使其传入 IHostingEnvironment 并使用一个ConstructorBuilder:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath ) // This line is wrong, but the correct path would be set here
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
string myString = Configuration["blah:blah:blah"];
虽然第二个解决方案可以工作,但这让我很烦恼,因为我认为在 .NET Core 2.0 中有一种更“正确”的方法可以做到这一点。有吗?
【问题讨论】:
标签: .net-core