Read the app settings with ASP.NET Core

In previous version of “ASP.NET”, we used to retrieve settings from the “web.config” by using the “ConfigurationManager” like this:

However, with “ASP.NET Core”, things get a little bit different, and I didn’t say “more complicated” but “different”. Indeed, now, the idea is to convert your app settings to a plain C# object but don’t worry, you won’t have to do this by yourself, “ASP.NET Core” will do it for you.

Say, you have the following “appSettings.json” file:

And you want to have access to these values from your C# code. The first thing to do is to create the corresponding class:

Note that while property names must match the name of the settings, the name of class does not have to.

To convert values from the JSON file to an object, add the following line in the “ConfigureServices” method or your startup class.

This way, now, you can directly inject these values in class managed by the DI engine of “ASP.NET Core”. For example:

You now have access to the object “appSettings” in your code and can access any of these properties.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.