You can find my all .Net core posts here.
In this series of posts, we will see some quick tips or tricks to use some specific things in .Net Core
In this post, we will see how to access configuration in the controller.
As we know, in .Net Core we have appsettings.json file to store the configuration related data.
For example, you have appsettings.json as below:
{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } }, "myFirstKey": "myFirstValue" }
From .Net Core 2.0 onwards, you are no more required to add new IConfiguration
in the Startup
constructor. Its implementation will be injected by the DI system and is already available in Startup.cs class:
But if you are targetting .Net Core lower than 2.0 then you need to add IConfiguration in Startup.cs.
Access Configuration in Controller
We can directly inject IConfigurationService into the controller as below:
public class HomeController : Controller { private IConfiguration _configuration; public HomeController(IConfiguration Configuration) { _configuration = Configuration; } }
That is it. You can now access the config from the HomeController.
For example, you want to use it in Contact action then access it as below:
public IActionResult Contact() { ViewBag.ConfigValue = _configuration["myFirstKey"]; }
As you can see below, myFirstValue which is the value of the key myFirstKey in the appsettings.json file.
Complex config structure
You can even have some complex structure in appsettings.json as below:
{ "MyConfigSection": { "MyFirstConfig": "Neel Bhatt", "MySecondConfig": { "MyFirstSubConfig": 27, "MySecondSubConfig": "Pune" } } }
To access this, write below code:
public IActionResult Contact() { // Option 1: Configuration using Key string ViewData["MySectionMyFirstConfig"] = _configuration["MyConfigSection:MyFirstConfig"]; // Option 2: Configuration using GetSection method ViewData["MySectionMySecondConfigMyFirstSubConfig"] = _configuration.GetSection("MyConfigSection").GetSection("MySecondConfig").GetSection("MyFirstSubConfig"); // Option 3: Mixture of Option 1 & Option 2 ViewData["MySectionMySecondConfigMySecondSubConfig"] = _configuration.GetSection("MyConfigSection")["MySecondConfig:MySecondSubConfig"]; return View(); }
Read the connection string
To read the connection string, you need to call it using the GetConnectionString method as shown below:
var connectionString = Configuration.GetConnectionString("myConnectionString");
Hope it helps.
You should avoid accessing the Configuration directly in the controllers, really you want to build an abstraction on top of the Configuration and inject that into your controllers.
LikeLike
Hi James, yes you are right. I just wanted to explain different ways to access configuration, one is for services(or normal class) and another is for controllers. It was just for the samples.
LikeLike