Threads I searched
My application is a .NET Core 3.1 app so I added the library System.Configuration.ConfigurationManager via NuGet to my project. My root folder contains a Web.Config with the following contents
<?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>
However, when I access ConfigurationManager.AppSettings[key] it's always empty. Also, Configurationmanager.AppSettings.AllKeys is empty and the count is 0, as if it's not being parsed.
Any ideas?
I'd like to add for anyone who comes here doesn't have the option to use the appsettings.json....
For me this problem manifest itself inside a UnitTest project. ConfigurationManager expects a file named ASSEMBLYNAME.dll.config, but the Unit Tests in .net core run under the name "testhost" so it looks for testhost.dll.config. Therefore you need to rename the generated config file to match what ConfigurationManager is looking for.
In your csproj file, add a build step like such...
<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>
Solution came from https://github.com/microsoft/testfx/issues/348
Okay, https://stackoverflow.com/users/392957/tony-abrams pointed me in the right direction.
So basically, I need an appsettings.json file (even if the Internet told me otherwise) and I defined it like this
{
"JobFolder": "App_Data/jobs",
"Interval": 5,
"Offset": 7200,
"Caching": 604800
}
Then, in the class where I need this I added a new constructor argument IConfiguration configuration which is already registered in the DI container, so no further action needed there.
Then, when I want to access the value, I can simply do _configuration.GetValue<string>("JobFolder") and have the value.
Thank you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With