Asp.Net Core MVC

ASP.Net Core Configuration – part 1 – appsettings.json & strongly typed configuration

Configuring an Asp.Net Core MVC is not a problem since Microsoft has come with a great API. It enables storing your key-value pairs in variety of ways, preserving the hierarchical character of your data.

In this post I will focus only on the most popular way of configuring an app. So, let’s talk about…

 Configuration Files (.json, .xml or .ini)

Let’s say we want to store connection string and some email messaging configuration in appsettings.json file.

Its content looks like this:

To read this data we will use two approaches

  • the simplest one (just reading the key-value pair) – to retrieve connection string
  • mapping hierarchical key-value pairs to POCO class – to retrieve email messages configuration

In both situations we need the following Nuget package:

  • Microsoft.Extensions.Configuration

BTW You can download code of both solutions from github: https://github.com/AGirlAmongGeeks/AspNetCoreMvc_ConfigurationSample

The simplest way

It’s perfect solution for reading individual configuration data.

To read configuration data, we need an object of ConfigurationBuilder class. The code is rather simple and similar to the one we have in Statup.cs of ASP.Net Core MVC project.

As you can see, we just have a builder to read from appsettings.json file. The above code supports changing enviroment (ex. from developer to production – I’ll disscuss it in more deep in near future) or using ‘Secrets’ (which mean storing some of your configuration locally, so it will not be commited accidently to repository – also will be discussed soon), but that’s not important now. In fact all we need to do is just create a ConfigurationBuilder instance and call its method Build().

Having this done, we go to the controller where we can simply call the above method to create a ‘configuration’ object and retrive configuration in (at least!) 3 ways!

And that’s it – all the above methods returns connection string from appsettings.json.

Strongly typed configuration

To retrieve more than one element from configuration file, I strongly recommend this solution.

First of all, we have to create a POCO class that reflects .json structure (of course it doesn’t have to be structure of the whole file – the class consist of only the fields we want to read from configuration file). In our case it will look like this:

Next, we go to the Startup.cs and we add the following line to the ConfigureServices(IServiceCollection services) method. That way, we make EmailMessages visible for controllers.

And the final step – in controller we add some EmailMessages object and a constructor with IOptions<EmailMessages> parameter :

And that’s it! Constructor fullfills our EmailMessages with appsettings.json configuration.

Other methods of reading configuration will appear as separated posts soon. Stay tuned!

Mem from https://memegenerator.net/

Share this: