TOC

The community is working on translating this tutorial into Polish, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Core Concepts:

Configuration

At some point in the development of your web application, you'll likely need a place to store some settings/options. There are a number of ways to accomplish this, but the recommended way is through the App Configuration mechanisms found in the .NET framework. We'll discuss how it works in this article.

appsettings.json and Web.config

If you have worked with previous versions of ASP.NET, before the Core framework was released, you may be used to working with Web.config files. They were previously used to store configuration settings, and they are still used by the ASP.NET Core framework, but they are mostly used for settings which are to be used by the webserver and not so much by the application itself.

In these Core Framework days, the most common place to store application settings is in the appsettings.json file. As the name indicates, this file is in the JSON format, while the Web.config file is XML-based.

When creating a new ASP.NET Core MVC application in Visual Studio, and even when using the Empty template, an appsettings.json file will be created for you. It will contain some default options related to logging etc., and it will likely look like this:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

I won't go into details about the JSON format - you may already know it from working with JavaScript, but if not, you can see that it's based on key/value pairs: A key (e.g. "AllowedHosts"), then a colon and then the value (in this case "*"). The value can either be a string or an object containing more key/values, as you can see with the "Logging" object.

You are free to edit these key/value pairs or add new ones. So, for instance, if you want to add a setting to hold the title of the website, you can simply add it to the appsettings.json file like this:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "WebsiteTitle": "My ASP.NET Core MVC Website"
}

As you can see, it's easy to add information in this simple format.

Accessing options from the appsettings.json file

With that in place, let's discuss how to actually access your options. It actually depends on where you need it, so lets talk about the various possibilities.

Accessing appsettings.json from the Controller

The framework will automatically pass your configuration settings to your Controllers, through a method called Dependency Injection (DI), but only if you specify a constructor with a parameter of the IConfiguration type. Be sure to include the Microsoft.Extensions.Configuration namespace first:

using Microsoft.Extensions.Configuration;

This will allow you to use the specify the constructor, like this:

public class HomeController : Controller  
{  
    private readonly IConfiguration _configuration;  
    public HomeController(IConfiguration configuration)  
    {  
_configuration = configuration;  
    }
    ....

By saving a reference to the IConfiguration object, you can now access configuration settings through all the methods of your Controller, like this:

public IActionResult Index()
{
    return Content("Welcome to " + _configuration.GetValue<string>("WebsiteTitle"));
}

In this case, we use the GetValue() method to retrieve the value we stored in the appsettings.json file.

Accessing appsettings.json from the Startup class

Some settings are needed when your application starts. We have previously talked quite a bit about the Startup class, found in the Startup.cs file, which is used for many things in an ASP.NET Core application. Accessing your settings in one of the Startup methods, e.g. ConfigureServices() or Configure(), is just as easy as doing it inside a Controller. In fact, the approach is the exact same:

public class Startup  
{  
    private readonly IConfiguration _configuration;  
    public Startup(IConfiguration configuration)  
    {  
_configuration = configuration;  
    }  
    public void ConfigureServices(IServiceCollection services)  
    {  
string websiteTitle = _configuration.GetValue<string>("WebsiteTitle"));  
services.AddMvc();      
    }
    ....

Accessing appsettings.json from Views

Since we just saw how to get app settings in the Controller, you can of course just pass these to the View from there. However, sometimes it's easier to access them directly from your View, whether it be a regular View or e.g. a _Layout View. This is also done using Dependency Injection, like this:

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

<h1>Index</h1>

Welcome to @(Configuration.GetValue<string>("WebsiteTitle"))

Sections

So far, we've only stored a simple string in our appsettings.json file, but as I mentioned in the beginning, a JSON value can just as easy be an object, allowing you to store multiple values under the same key. So for instance, if we wanted to store more information about our website than just the title, we could change our entry in the appsettings.json file to something like this:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "Website": {
    "Title": "My ASP.NET Core MVC Website",
    "Version": 1.01
  }
}

As you can see, we now have information about our website in an object containing two properties: Title and Version. This would of course make more sense if we had more properties, but as an illustration of how it works it will do just fine.

An object in the JSON format translates into a section when you want to retrieve the properties of it. So we need to retrieve the section ("Website") before we can fetch one of the properties - here's an example:

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

<h1>Index</h1>

Welcome to @(Configuration.GetSection("Website").GetValue<string>("Title"))
<br />
Version: @(Configuration.GetSection("Website").GetValue<string>("Version"))

The website information has now been grouped into its own section - this is especially useful if you have a LOT of settings in your appsettings.json file.

Summary

As we have seen in this article, it's fairly easy to work with the Configuration mechanism found in the ASP.NET Framework, making it easy for you to store and access application settings. However, the approach we have used here is the simple version, where we use hardcoded strings when accessing the various sections and settings. This is generally not recommended - we should instead use the Options pattern, which builds on top of the Configuration mechanism. We'll learn more about it in the next article.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!