無法確定如何讀取startup.cs之外的appsettings.json值。我想這樣做的是,例如,在_Layout.cshtml,從配置中添加站點名稱:訪問控制器類中的appsettings.json值
例如:
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; }
也許我讀的文檔錯誤的,但我似乎無法揭露啓動類之外的配置對象。
你看到這一點:http://stackoverflow.com/questions/31453495/how-to-read- appsettings-values-from-config-json-in-asp-net-vnext –