我已经在我的第一个ASP.NET(Core 2.1)应用程序中添加了一些自定义设置,但我不知道如何从C#访问它。我想我没有正确地初始化它,有人可以看一下吗?
appsettings.js:
"DatabaseSettings":
{
"Hostname": "localhost",
"Port": "12345",
"DbName": "myDatabase"
}
以下是它的课程:
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);
}
}
属性返回null。
答案 0 :(得分:4)
只需将您的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);
}
}
答案 1 :(得分:2)
使用services.Configure<T>()
添加设置后,可以使用IOptions<T>
将其注入其他类。您还可以通过在启动类的IOptions<T>
方法中指定Configure()
来引用它。在你的情况下:
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);
}
答案 2 :(得分:2)
添加到Nicholas Reynolds answer 你可以用
var sett = new DatabaseSettings();
Configuration.GetSection("DatabaseSettings").Bind(sett);
或者如果你想获得单一价值,你可以使用
var hostname = Configuration.GetSection("DatabaseSettings:Hostname");