How to read values from the Appsettings.json file?
How to read values from the Appsettings.json file?
451
06-Mar-2023
Updated on 08-Jul-2023
Aryan Kumar
08-Jul-2023To read values from the appsettings.json file in ASP.NET Core, you can use the
IConfigurationinterface. TheIConfigurationinterface provides a way to access configuration data from within your application.To read a value from the appsettings.json file, you can use the
[]operator. The[]operator takes two parameters: the name of the value that you want to read and the default value that you want to use if the value is not found in the configuration file.The following is an example of how to read a value from the appsettings.json file:
C#
In this example, we first create a configuration object by calling the
ConfigurationBuilder()constructor. We then add the command-line arguments to the configuration object by calling theAddCommandLine()method. Finally, we get the database connection string from the configuration object by calling the["ConnectionStrings:MyDatabase"]property.We can then use the database connection string to connect to the database and do something with the database.
If the value that you are trying to read is not found in the configuration file, the
IConfigurationinterface will return the default value that you specified.You can also use the
GetSection()method to read a section from the appsettings.json file. A section is a group of related configuration values. For example, you could have a section for database connection strings, a section for API keys, and so on.The following is an example of how to read a section from the appsettings.json file:
C#
In this example, we first create a configuration object by calling the
ConfigurationBuilder()constructor. We then add the command-line arguments to the configuration object by calling theAddCommandLine()method. Finally, we get the database connection strings section from the configuration object by calling theGetSection()method.We can then get the database connection string from the section by calling the
["MyDatabase"]property.If the section that you are trying to read is not found in the configuration file, the
IConfigurationinterface will return null.