.NET 6.0 - get appsettings.json values from class library. I have a .NET 6.0 web api project and another is class library.
I want to read some settings into class library.
We have appsettings.json inside a web api project. How can I read those values inside a class library?
Could you please provide me proper code snippets
I am new to .net core 6 and also dependency injections and all
In your class library where you want to read in the values, you should be able to access the json-file with ConfigurationBuilder. First, define location of appsettings.json:
string filePath = @"C:\MyDir\MySubDirWhereAppSettingsIsLocated\appSettings.json"; //this is where appSettings.json is located
Then use the filePath when trying to access file:
IConfiguration myConfig = new ConfigurationBuilder()
.SetBasePath(Path.GetDirectoryName(filePath))
.AddJsonFile("appSettings.json")
.Build();
Then afterwards, you can access the individual values inside appsettings.json like this:
string myValue = myConfig.GetValue<string>("nameOfMyValue");
Beware that you need to import the NuGet-package Microsoft.Extensions.Configuration.Json
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