如何从 appsettings.js 加载自定义设置

How to load custom settings from appsettings.js

我已经在我的第一个 ASP.NET (Core 2.1) 应用程序中添加了一些自定义设置,但我不知道如何从 C# 访问它。我想我没有正确初始化它,有人可以看一下吗?

appsettings.js:

"DatabaseSettings": 
{
    "Hostname": "localhost",
    "Port": "12345",
    "DbName": "myDatabase"
}

这里是 class:

public class DatabaseSettings
{
    public string Hostname { get; set; }
    public int Port { get; set; }
    public string DbName { get; set; }
}

Startup.cs:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.Configure<DatabaseSettings>(Configuration.GetSection("DatabaseSettings"));
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
            app.UseDeveloperExceptionPage();
        app.UseMvc();
        var databaseSettings = Configuration.Get<DatabaseSettings>();
        Mongo.Initialize("mongodb://" + databaseSettings.Hostname + ":" + databaseSettings.Port, databaseSettings.DbName);
    }
}

属性return为空。

使用 services.Configure<T>() 添加设置后,可以使用 IOptions<T> 将其注入其他 classes。您也可以通过在启动 class 的 Configure() 方法中指定 IOptions<T> 来引用它。你的情况:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions<DatabaseSettings> settings)
{
    if (env.IsDevelopment())
        app.UseDeveloperExceptionPage();
    app.UseMvc();
    var databaseSettings = settings.Value;
    Mongo.Initialize("mongodb://" + databaseSettings.Hostname + ":" + databaseSettings.Port, databaseSettings.DbName);
}

只需将您的 Configuration 变量设为全局即可。你可以把它放在启动的任何地方

public class Startup
{
    public IConfiguration Configuration { get; set; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
   public void ConfigureServices(IServiceCollection services)
   {
    services.AddMvc();
    services.Configure<DatabaseSettings>(Configuration.GetSection("DatabaseSettings"));
   }

  public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  {
    if (env.IsDevelopment())
        app.UseDeveloperExceptionPage();
    app.UseMvc();
    var settingsSection = Configuration.GetSection("DatabaseSettings");
    var settings = settingsSection.Get<DatabaseSettings>();
    Mongo.Initialize("mongodb://" + settings.Hostname + ":" + settings.Port, settings.DbName);
  }
}

添加到 你可以使用

var sett = new DatabaseSettings();
Configuration.GetSection("DatabaseSettings").Bind(sett);

或者如果你想获得单个值,你可以使用

var hostname = Configuration.GetSection("DatabaseSettings:Hostname");