.net-core - .NET Core 2.0 处理多个项目时的 appsettings.json 文件位置

标签 .net-core

我正在开发一个由多个项目组成的 .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 构造函数。我的理解是,这是从 appsettings.json 文件中读取值的 .NET Core 2.0 方式:
    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 中有一种更“正确”的方法可以做到这一点。在那儿?

最佳答案

我想通了是怎么回事。在launch.json 文件中,我没有为cwd 参数设置正确的路径。这就是 Startup() 在错误的位置寻找 appsettings.json 文件的原因。

关于.net-core - .NET Core 2.0 处理多个项目时的 appsettings.json 文件位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49886920/

相关文章:

c# - 如何捆绑.Net Core API + Angular 前端

c# - 根据请求参数在运行时创建 EF Core DbContext

azure - 绑定(bind) : The edit bindings button (. ..) 在 azure devops 中不可见

asp.net-core - 在 .Net Core WebAPI 上强制执行强制请求 header ?

c# - Asp.NET Core 如何设置 maxJsonLength

css - 删除 css 包中的注释而不缩小文件

c# - AutoFac/.NET Core - 注册 DBcontext

.net-core - 大众交通中的 InMemoryTransportCache 发生了什么?

c# - X509Certificate2.FriendlyName 属性无法检索 Linux 上的证书标签

c# - 在单独的表 EF Core 中插入 2 个项目