在控制器 类 中访问 appsettings.json 个值
Access appsettings.json values in controller classes
无法弄清楚如何读取 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 对象 class。
在你的Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfiguration>(Configuration);
}
然后在你的控制器中:
public class ValuesController : Controller
{
IConfiguration configuration;
public ValuesController(IConfiguration configuration)
{
this.configuration = configuration;
}
}
无法弄清楚如何读取 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 对象 class。
在你的Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfiguration>(Configuration);
}
然后在你的控制器中:
public class ValuesController : Controller
{
IConfiguration configuration;
public ValuesController(IConfiguration configuration)
{
this.configuration = configuration;
}
}