无法弄清楚如何读取startup.cs之外的appsettings.json值。我想做的是,例如,在_Layout.cshtml中,从配置中添加站点名称:
例如:
ViewData["SiteName"] = Configuration.GetValue<string>("SiteSettings:SiteName");
甚至更好:
public class GlobalVars {
public static string SiteName => Configuration.GetValue<string>("SiteSettings:SiteName");
}
到目前为止,这是我的代码:
[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; }
也许我正在阅读文档错误,但我似乎无法在Startup类之外公开Configuration对象。
答案 0 :(得分:24)
在你的Startup.cs
中PartialFunction[Int, String]
然后在你的控制器中:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfiguration>(Configuration);
}