Having trouble figuring out how to read appsettings.json values outside of the startup.cs. What I would like to do is, for instance, is in the _Layout.cshtml, add the site name from the config:
For example:
ViewData["SiteName"] = Configuration.GetValue<string>("SiteSettings:SiteName");
Or even better:
public class GlobalVars { public static string SiteName => Configuration.GetValue<string>("SiteSettings:SiteName"); }
Here's my code thus far:
[appsettings.json]
"SiteSettings": { "SiteName": "MySiteName" }
[startup.cs]
public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); var siteName = Configuration.GetValue<string>("SiteSettings:SiteName"); } public IConfigurationRoot Configuration { get; }
Maybe I'm reading the docs wrong, but I can't seem to expose the Configuration object outside of the Startup class.
Using IConfiguration The IConfiguration is available in the dependency injection (DI) container, so you can directly access JSON properties by simply injecting IConfiguration in the constructor of a controller or class. It represents a set of key/value application configuration properties.
There are two methods to retrieve our values, string dbConn = configuration. GetSection("MySettings"). GetSection("DbConnection").
In your Startup.cs
public void ConfigureServices(IServiceCollection services) { services.AddSingleton<IConfiguration>(Configuration); }
then in your controller:
public class ValuesController : Controller { IConfiguration configuration; public ValuesController(IConfiguration configuration) { this.configuration = configuration; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With