Skip to content

The New Configuration Model in ASP.NET Core

🏷️ ASP.NET Core

旧方法

Web.Config

xml
<appSettings>
    <add key="SmtpServer" value="0.0.0.1" />
    <add key="SmtpUser" value="user@company.com" />
    <add key="SmtpPass" value="12345678" />
    <add key="SmtpPort" value="25" />
    <!-- More Settings -->
</appSettings>

取值:

csharp
ConfigurationManager.AppSettings["SmtpServer"];

新方法

JSON:

json
{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Verbose",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "Smtp": {
    "Server": "0.0.0.1",
    "User": "user@company.com",
    "Pass": "123456789",
    "Port": "25"
  }
}

创建对应的 Model

csharp
public class SmtpConfig
{
    public string Server { get; set; }
    public string User { get; set; }
    public string Pass { get; set; }
    public int Port { get; set; }
}

在 Startup.cs 中读取配置文件

constructor 方法:

cs
var builder = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .AddEnvironmentVariables();
Configuration = builder.Build();

ConfigureServices 方法 (将配置项映射到 Model 的属性):

cs
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<SmtpConfig>(Configuration.GetSection("Smtp"));
    services.AddMvc();
    //Other services
}

使用配置项 (Controller 的构造函数依赖注入):

cs
public class HomeController : Controller
{
    public SmtpConfig SmtpConfig { get; }
    public HomeController(IOptions<SmtpConfig> smtpConfig)
    {
        SmtpConfig = smtpConfig.Value;
    }
    //Action Controller
}
根据环境自动变更配置文件:

创建 QA 环境的配置文件: appsettings.qa.json

json
{
    "Smtp": {
        "Server": "0.0.0.5",
        "User": "usersmtp@company.com",
        "Pass": "Ke!2546hg#$",
        "Port": "427"
    }
}

在项目属性的环境变量中设置 [Hosting:Environment] ,值为 [qa]

修改 Startup.cs 文件,使其加载 qa 环境的配置文件,覆盖默认配置文件的设定值;

csharp
public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
    Configuration = builder.Build();
}

原文:The New Configuration Model in ASP.NET Core