Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET 6.0 - read appsettings.json values from class library

.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

like image 797
dev Avatar asked Mar 16 '26 15:03

dev


1 Answers

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

like image 166
mnc Avatar answered Mar 20 '26 17:03

mnc