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:

{
    "ConnectionStrings": {
        "DefaultConnection": "Server=.\\;Database=MyPetDB..."
    },
    "EmailMessages": {
        "SendingEnabled": "True",
        "FirstMessage": {
            "Title": "Here is the title of the first message",
            "Message": "Here is the content of the first message"
        },
        "SecondMessage" : {
            "Message": "Here is the second message",
            "Title": "Here is another title, dedicated..."
        }
    },
    "Logging": {
       ...
    }
}

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.

public static IConfigurationRoot GetConfiguration(string path, string environmentName = null, bool addUserSecrets = false)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(path)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

    if (!String.IsNullOrWhiteSpace(environmentName))
    {
        builder = builder.AddJsonFile($"appsettings.{environmentName}.json", optional: true);
    }

    builder = builder.AddEnvironmentVariables();

    if (addUserSecrets)
    {
        builder.AddUserSecrets(); // requires adding Microsoft.Extensions.Configuration.UserSecrets from NuGet.
    }

    return builder.Build();
}

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!

var configuration = ConfigurationHelper.GetConfiguration(Directory.GetCurrentDirectory());

//3 ways to get the same configuration.

var connectionString = configuration.GetConnectionString("DefaultConnection");

var connectionString2 = configuration.GetSection("ConnectionStrings")["DefaultConnection"];

var connectionString3 = configuration.GetValue<string>("ConnectionStrings:DefaultConnection");

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:

public class EmailMessages
{
    public bool SendingEnabled { get; set; }
    public FirstMessage FirstMessage { get; set; }
    public SecondMessage SecondMessage { get; set; }
}

public class FirstMessage
{
    public string Title { get; set; }
    public string Message { get; set; }
}

public class SecondMessage
{
    public string Message { get; set; }
    public string Title { get; set; }
}

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.

services.Configure<EmailMessages>(Configuration.GetSection("EmailMessages"));

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

private EmailMessages EmailMessages { get; set; }

public HomeController(IOptions<EmailMessages> config)
{
    EmailMessages = config.Value;
}


public IActionResult Index()

{
     var firstMessage = EmailMessages.FirstMessage;

}

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: