认为我的startup.cs有问题,因为我没有从<IOption> config
中获取任何值
所以..我们有我们的 appsettings.json
"Config": {
"ApplicationName": "some name",
"ConnectionString": "someconstring",
"Version": "1.0.0"
},
这是我们的模型
public class Config
{
public string ApplicationName { get; set; }
public string ConnectionString { get; set; }
public string Version { get; set; }
}
startup.cs
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public static IConfiguration Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Add functionality to inject IOptions<T>
services.AddOptions();
// Add our Config object so it can be injected
services.Configure<Config>(Configuration);
}
然后在我们的控制器中,我尝试加载这些数据,但不幸的是,它们仍然为空。
private IOptions<Config> config;
public CompaniesController(IOptions<Config> config)
{
this.config = config;
}
我尝试用类似的方式更改startup.cs
services.Configure<Config>(options =>
{
options.ConnectionString = Configuration.GetSection("Config:ConnectionString").Value;
});
但这似乎不起作用。
资源我一直在使用:
https://dzone.com/articles/dynamic-connection-string-in-net-core
https://stackoverflow.com/questions/31453495/how-to-read-appsettings-values-from-json-file-in-asp-net-core
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-2.2
但是很明显,我在这里缺少关键点。
编辑:我正在使用ASP.Net Core 2.0
edit2:
Program.cs
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
整个 Appsettings.json 文件
{
"Config": {
"ApplicationName": "somename",
"ConnectionString": "someconstring",
"Version": "1.0.0"
},
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
}
}
}
答案 0 :(得分:4)
services.Configure<Config>(Configuration)
;
此行无法达到预期的效果,因为您要查找的JSON属性嵌套在Config
文件中的appsettings.json
属性下。为了加载这些值,您需要使用GetSection
来抓取Config
部分,并将 that 传递到Configure<TOptions>
方法中:
services.Configure<Config>(Configuration.GetSection("Config"));
答案 1 :(得分:0)
services.Configure<Config>(options =>
{
options.ConnectionString = Configuration.GetValue<string>("Config:ConnectionString");
options.ApplicationName = "test";
});
如果您想更细致地配置您的选项。