每次我撥打Configuration.GetSection
時,返回對象的Value
屬性始終爲空。Configuration.GetSection總是返回null
我Startup
構造
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
this.Configuration = builder.Build();
}
我ConfigureServices
方法
public void ConfigureServices(IServiceCollection services)
{
services.Configure<SqliteSettings>(opts => Configuration.GetSection("SqliteSettings").Bind(opts));
services.AddOptions();
services.AddMvc();
}
我appsettings.json
{
"SqliteSettings": {
"DataSource": "C:\\db.sqlite",
"NewDatabase": true,
"Version": 3
}
}
類我使用的定義SqliteSettings
public class SqliteSettings
{
public string DataSource { get; set; }
public bool? NewDatabase { get; set; }
public int? Version { get; set; }
public string Password { get; set; }
public long? CacheSize { get; set; }
// More properties
}
我在想JSON可能需要有相同數量的屬性來匹配,或者它可能與數據類型定義有關,但也許這些是完全不相關的。
工作對我來說Unforunately,沒有工作,但順序放置可能解決了會在未來發生的錯誤。 'Configuration.GetSection'仍然返回,'.Value'爲空。 –
你能分享你如何調用'.Value'嗎? – Ali
要查看我是否獲取JSON,只需執行'var x = Configuration.GetSection(「SqliteSettings」);'然後在Visual Studio中檢查x,特別是爲'Value'。 –