无法弄清楚如何读取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");
}
这是迄今为止我的代码:
[应用程序设置.json]
"SiteSettings": {
"SiteName": "MySiteName"
}
[启动.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 对象。
在您的 Startup.cs 中
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfiguration>(Configuration);
}
然后在你的控制器中:
public class ValuesController : Controller
{
IConfiguration configuration;
public ValuesController(IConfiguration configuration)
{
this.configuration = configuration;
}
}
想在这篇文章中添加更新,因为我在搜索 Dot Net Core 8 MVC 时遇到了它: 现在,您将以下内容添加到 Program.cs 中的构建器(取代了 Startup.cs):
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
// Add IConfiguration to the container
builder.Services.AddSingleton(builder.Configuration);
var app = builder.Build();
然后将以下内容添加到带有记录器的控制器顶部:
private readonly ILogger<HomeController> _logger;
private readonly IConfiguration _appsettings;
public HomeController(ILogger<HomeController> logger, IConfiguration appsettings)
{
_logger = logger;
_appsettings = appsettings;
}
添加这些后,您可以以数组格式访问 appsettings.json 值,如下所示:
var businessLocation = _appsettings["Locations:101"];
其中appsettings.json格式如下(并获取值1):
"Locations": {
"101": "1",
"202": "2",
"303": "3"
},