Friday, October 26, 2018

.NET Core MVC: Get values from Configuration file

The following code initially exists in the Startup.cs file:

public Startup(IConfiguration configuration)
{
Configuration = configuration;
}


This implies that the configuration will be injected in other classes found in your project. As a result, you can get the configuration from any class files.
Example: Accessing configuration in controller:
1. define a property of type IConfiguration in the class
2. inject IConfiguration parameter in your constructor
3. access the Configuration property defined from any method


public IConfiguration Configuration;

public HomeController(IConfiguration configuration)
{
Configuration = configuration;
}

public IActionResult Index()
{
ViewData["test"] = Configuration["Logging:LogLevel:Default"];


Sample appsettings.json file:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "server=localhost;port=3307;database=test;user=root;password=;Persist Security Info=False;SSL Mode =None;"
  },
  "AllowedHosts": "*"
}

No comments:

Post a Comment