ConfigurationManager.AppSettings 始终为空

Mus*_*abe 2 .net c# .net-core

我搜索的主题

我的应用程序是一个 .NET Core 3.1 应用程序,因此我System.Configuration.ConfigurationManager通过 NuGet将该库添加到我的项目中。我的根文件夹包含Web.Config以下内容

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.web>
        <compilation debug="true"  />
        <httpRuntime  />
    </system.web>
    <appSettings>
        <!-- Folder of LogParser job-configurations -->
        <add key="JobFolder" value="App_Data/jobs"/>
        <!-- Background task execution interval in seconds -->
        <add key="Interval" value="5"/>
        <!-- Message offset in seconds. Reads older messages to circumvent log4net timestamp bug -->
        <add key="Offset" value="7200"/>
        <!-- Caching duration for hash MemoryCache in seconds. Default is 604800 (7 days) -->
        <add key="Caching" value="604800"/>
    </appSettings>
</configuration>
Run Code Online (Sandbox Code Playgroud)

但是,当我访问ConfigurationManager.AppSettings[key]它时,它总是空的。此外,Configurationmanager.AppSettings.AllKeys为空且计数为 0,就好像它没有被解析一样。

有任何想法吗?

smi*_*reg 6

我想为来到这里的任何人添加都没有使用 appsettings.json 的选项....

对我来说,这个问题在 UnitTest 项目中表现出来。ConfigurationManager 需要一个名为 ASSEMBLYNAME.dll.config 的文件,但 .net 核心中的单元测试在名称“testhost”下运行,因此它查找 testhost.dll.config。因此,您需要重命名生成的配置文件以匹配 ConfigurationManager 正在寻找的内容。

在您的 csproj 文件中,添加这样的构建步骤...

<Target Name="CopyAppConfig" AfterTargets="Build" DependsOnTargets="Build">
    <CreateItem Include="$(OutputPath)$(AssemblyName).dll.config">
      <Output TaskParameter="Include" ItemName="FilesToCopy"/>
    </CreateItem>
    <Copy SourceFiles="@(FilesToCopy)" DestinationFiles="$(OutputPath)testhost.dll.config" />
</Target>
Run Code Online (Sandbox Code Playgroud)

解决方案来自 https://github.com/microsoft/testfx/issues/348

  • 如果使用 Rider 或者 VS 内的 Resharper 测试运行程序,您还需要以下内容: `&lt;Copy SourceFiles="@(FilesToCopy)" DestinationFiles="$(OutputPath)ReSharperTestRunner.dll.config" /&gt;` 如果没有不起作用,进入“ConfigurationManager.AppSettings”并查看“s_configSystem._completeConfigRecord.ConfigContext”并找到“ExePath”变量。 (2认同)

Mus*_*abe 0

好的, https: //stackoverflow.com/users/392957/tony-abrams为我指明了正确的方向。

所以基本上,我需要一个appsettings.json文件(即使互联网告诉我不是这样),我这样定义它

{
    "JobFolder": "App_Data/jobs",
    "Interval": 5,
    "Offset": 7200,
    "Caching": 604800
}
Run Code Online (Sandbox Code Playgroud)

然后,在我需要这个的类中,我添加了一个新的构造函数参数,IConfiguration configuration该参数已经在 DI 容器中注册,因此不需要进一步的操作。

然后,当我想要访问该值时,我可以简单地执行_configuration.GetValue<string>("JobFolder")并获得该值。

谢谢。