c# - 无法读取 dotnet 核心中链接的 appsettings.json 文件中的值

标签 c# asp.net-core .net-core appsettings

在 aspnetcore 2.0 项目中,我试图在我的 Web 应用程序和几个 xunit 测试项目中设置一个共享的 appsettings.json 文件。

首先,当我将 appsettings.json “定期”单独添加到我的项目时,一切正常。但是,当我尝试添加单个 时引用/链接 来自不同路径的文件,在运行时不会读出这些值。

为了进行设置,对于每个项目,我将链接文件添加到 .csproj:

<ItemGroup>
    <Content Include="..\Shared\appsettings.json">
        <Link>appsettings.json</Link>
        <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
</ItemGroup>

在每次构建时,我都可以验证它是否很好地输出到 /bin/Debug/netcoreapp2.0目录:

Screenshot of output directory

问题是,在读取它时,无论是通过我的 webapi 的默认启动还是在测试中,设置值始终为空。我正在使用强类型配置。在 webapi 项目中,我使用的是 WebHost.CreateDefaultBuilder()使用 aspnetcore 2.0 约定(在幕后查看 hostingEnvironment.EnvironmentName ,dotPeek 告诉我)。

但在测试项目的情况下,也会发生同样的情况。这一切都可以通过我的全局测试装置中的以下示例来解释:

var builder = new ConfigurationBuilder()
    // .SetBasePath(???)
    .AddJsonFile("appsettings.json");

var configuration = builder.Build();

var settings = new FooSettings();
configuration.GetSection("FooSettings").Bind(settings);

if (settings == null) throw new Exception("Could not find or parse 'appsettings.json'");

// The problem: always fails on this check
if (string.IsNullOrEmpty(settings.Bar)) throw new Exception("Could not find or parse 'FooSettings'");

问题在上述示例的最后一行进行了注释。同样,当我直接将 appsettings.json 文件添加到项目根目录而不是将其添加为共享文件夹的链接引用时,它可以完美运行。我假设我必须以不同的方式更改 .csproj 配置或使用不同的 .SetBasePath(???) .但对于两者,我都在努力实现它。

问题:我该怎么做才能使 已链接 appsettings 文件可以在我的所有项目中正确读取吗?

注意我找到了其他几个帖子,但找不到任何具有匹配答案的帖子,特别是针对 dotnetcore。

最佳答案

我在 Program 中添加了一些代码后它开始工作了(感谢@mr_squall 的指导..):

     public static void Main(string[] args)
        {
            CreateHostBuilder(args)
#if !DEBUG
                .UseContentRoot(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location))
#endif
                .Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    config.SetBasePath(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

关于c# - 无法读取 dotnet 核心中链接的 appsettings.json 文件中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49888073/

相关文章:

c# - 将 Hashalgorithm 与 ReadOnlySpan<byte> 结合使用

c# - 使用 javascript 从 ListView 获取隐藏字段的值

c# - 单击按钮激活/停用 javascript

c# - 在 C# 中生成 XML 文档哈希

c# - 当 SelectedIndex 属性更改时,ListBox 的 SelectedItem 属性会更改吗?

Azure 应用服务 - 传入连接激增但未生成请求

c# - 包 'Microsoft.EntityFrameworkCore.Tools.DotNet 1.0.0-msbuild2-final' 具有项目不支持的包类型 'DotnetCliTool'

c# - 有没有更优雅的方法使用 system.text.json 从 JSON 对象获取特定值

asp.net-mvc - 我可以使用 Entity Framework 6(不是 Entity Framework 核心)开发 Asp.net 核心 MVC 应用程序吗?

c# - 核心 3.1 - 绑定(bind) Body 中的一些属性和 Header 中的其他一些属性