.NET Core 中的整个配置方法非常灵活,但一开始并不明显。用一个例子可能最容易解释:
假设 appsettings.json 文件如下所示:
{
"option1": "value1_from_json",
"ConnectionStrings": {
"DefaultConnection": "Server=,\\SQL2016DEV;Database=DBName;Trusted_Connection=True"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}
要从 appsettings.json 文件中获取数据,您首先需要在 Startup.cs 中设置ConfigurationBuilder,如下所示:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see https://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets<Startup>();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
然后您可以直接访问配置,但创建选项类来保存该数据会更简洁,然后您可以将其注入控制器或其他类。这些选项类中的每一个都代表 appsettings.json 文件的不同部分。
在此代码中,连接字符串被加载到ConnectionStringSettings 类中,而另一个选项被加载到MyOptions 类中。 .GetSection 方法获取 appsettings.json 文件的特定部分。同样,这是在 Startup.cs 中:
public void ConfigureServices(IServiceCollection services)
{
... other code
// Register the IConfiguration instance which MyOptions binds against.
services.AddOptions();
// Load the data from the 'root' of the json file
services.Configure<MyOptions>(Configuration);
// load the data from the 'ConnectionStrings' section of the json file
var connStringSettings = Configuration.GetSection("ConnectionStrings");
services.Configure<ConnectionStringSettings>(connStringSettings);
这些是加载设置数据的类。请注意属性名称如何与 json 文件中的设置配对:
public class MyOptions
{
public string Option1 { get; set; }
}
public class ConnectionStringSettings
{
public string DefaultConnection { get; set; }
}
最后,您可以通过将 OptionsAccessor 注入控制器来访问这些设置,如下所示:
private readonly MyOptions _myOptions;
public HomeController(IOptions<MyOptions > optionsAccessor)
{
_myOptions = optionsAccessor.Value;
var valueOfOpt1 = _myOptions.Option1;
}
一般来说,整个配置设置过程在 Core 中是完全不同的。 Thomas Ardal 在他的网站上有一个很好的解释:http://thomasardal.com/appsettings-in-asp-net-core/
Configuration in ASP.NET Core in the Microsoft documentation还有更详细的解释。
注意:这一切在 Core 2 中都发生了一些变化,我需要重新审视上面的一些答案,但与此同时,this Coding Blast entry by Ibrahim Šuta 是一个很好的介绍,有很多例子。
注意第 2 点:使用上述方法很容易犯一些配置错误,如果不适合您,请查看 this answer。