不确定我在这里错过了什么,但我无法从我的应用程序设置中获得值。Json在我的。net核心应用程序。我有我的appsettings。json:
{
"AppSettings": {
"Version": "One"
}
}
启动:
public class Startup
{
private IConfigurationRoot _configuration;
public Startup(IHostingEnvironment env)
{
_configuration = new ConfigurationBuilder()
}
public void ConfigureServices(IServiceCollection services)
{
//Here I setup to read appsettings
services.Configure<AppSettings>(_configuration.GetSection("AppSettings"));
}
}
模型:
public class AppSettings
{
public string Version{ get; set; }
}
控制器:
public class HomeController : Controller
{
private readonly AppSettings _mySettings;
public HomeController(IOptions<AppSettings> settings)
{
//This is always null
_mySettings = settings.Value;
}
}
_mySettings总是空的。我是不是遗漏了什么?
appsetting.json
{
"Settings": {
"ProjectName": "Sample Project"
}
}
定义一个具有相同属性名的类:
public class Settings
{
public string ProjectName { get; set; }
}
在Startup.cs中添加配置:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<Settings>(Configuration.GetSection("Settings"));
}
注入控制器:
public class TestController : Controller
{
private readonly Settings _settings;
public TestController(IOptions<Settings> settings)
{
_settings = settings.Value;
}
[AllowAnonymous]
public async Task<IActionResult> test()
{
var _projectname = _settings.ProjectName;
return View();
}
}
再加上David Liang对Core 2.0的回答——
appsettings。json文件链接到ASPNETCORE_ENVIRONMENT变量。
ASPNETCORE_ENVIRONMENT可以设置为任何值,但是框架支持三个值:Development、Staging和Production。如果没有设置ASPNETCORE_ENVIRONMENT,它将默认为Production。
对于这三个值,这些appsettings.ASPNETCORE_ENVIRONMENT。json文件支持开箱即用- appsettings.Staging。appsettings.Development.json和appsettings.Production.json
以上三个应用程序设置json文件可用于配置多个环境。
示例- appsettings.Staging.json
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"System": "Information",
"Microsoft": "Information"
}
},
"MyConfig": "My Config Value for staging."
}
使用Configuration["config_var"]检索任何配置值。
public class Startup
{
public Startup(IHostingEnvironment env, IConfiguration config)
{
Environment = env;
Configuration = config;
var myconfig = Configuration["MyConfig"];
}
public IConfiguration Configuration { get; }
public IHostingEnvironment Environment { get; }
}
我在WPF中遇到了类似的问题。NET Framework 5.0)
我所要做的就是登记。
services.AddSingleton<IConfiguration>(_configuration);
配置本身是这样配置的(在App.xaml.cs中):
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
_configuration = builder.Build();