Top Menu

Tag Archives Tip of the Week

You defined your config structure in appsetings.json file, and you what to access this data in a Controller in your ASP.NET MVC or WebAPI project based on .NET Core 2.0. There are a couple of options, but one of the easiest is that.

The example structure of your configuration in appsetings.json file is below.


"MySection": {
"MyFirstConfig": "Secret string",
"MySecondConfig": {
"MyFirstSubConfig": true,
"MySecondSubConfig": 32

Using built-in support for Dependency Injection, you can inject configuration data to Controller. Use AddSingleton method to add a singleton service in Startup.cs file. Just add services.AddSingleton(Configuration); in ConfigureServices.


[csharp]public void ConfigureServices(IServiceCollection services)

In your Controller declare IConfiguration variable, and assign configuration in a constructor. To retrieve configuration data at Controller use:

  • _configuration["MySection:MyFirstConfig"] (each configuration key separated by “:”) or
  • _configuration.GetSection("MySection").GetSection("MySecondConfig").GetSection("MyFirstSubConfig") (each configuration key parsed by GetSection method) or
  • _configuration.GetSection("MySection")["MySecondConfig:MySecondSubConfig"] (mixed version – GetSection method with you section name as variable, and next configuration keys separated by “:” as Index).

Do not forget about using Microsoft.Extensions.Configuration; at the beginning 😉


[csharp]using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace WebApplication1.Controllers
public class HomeController : Controller
private IConfiguration _configuration;

public HomeController(IConfiguration Configuration)
_configuration = Configuration;

public IActionResult Index()
// Read configuration using Key string
ViewData["MySectionMyFirstConfig"] = _configuration["MySection:MyFirstConfig"];

// Read configuration using GetSection method
ViewData["MySectionMySecondConfigMyFirstSubConfig"] = _configuration.GetSection("MySection").GetSection("MySecondConfig").GetSection("MyFirstSubConfig");

// Read configuration using mixed options with GetSection method and Key string
ViewData["MySectionMySecondConfigMySecondSubConfig"] = _configuration.GetSection("MySection")["MySecondConfig:MySecondSubConfig"];

return View();

Example output:


MySectionMyFirstConfig <strong>@ViewData["MySectionMyFirstConfig"]</strong><br />
MySectionMySecondConfigMyFirstSubConfig <strong>@ViewData["MySectionMySecondConfigMyFirstSubConfig"]</strong><br />
MySectionMySecondConfigMySecondSubConfig <strong>@ViewData["MySectionMySecondConfigMySecondSubConfig"]</strong>

Source code with this example you can find on my GitHub account: