不确定我在这里错过了什么,但我无法从我的应用程序设置中获得值。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总是空的。我是不是遗漏了什么?
在我的例子中,它就像在Configuration对象上使用Bind()方法一样简单。然后将对象作为单例添加到DI中。
var instructionSettings = new InstructionSettings();
Configuration.Bind("InstructionSettings", instructionSettings);
services.AddSingleton(typeof(IInstructionSettings), (serviceProvider) => instructionSettings);
Instruction对象可以非常复杂。
{
"InstructionSettings": {
"Header": "uat_TEST",
"SVSCode": "FICA",
"CallBackUrl": "https://UATEnviro.companyName.co.za/suite/webapi/receiveCallback",
"Username": "s_integrat",
"Password": "X@nkmail6",
"Defaults": {
"Language": "ENG",
"ContactDetails":{
"StreetNumber": "9",
"StreetName": "Nano Drive",
"City": "Johannesburg",
"Suburb": "Sandton",
"Province": "Gauteng",
"PostCode": "2196",
"Email": "ourDefaultEmail@companyName.co.za",
"CellNumber": "0833 468 378",
"HomeNumber": "0833 468 378",
}
"CountryOfBirth": "710"
}
}
这里是一个关于。net框架和Core: web的抽象。Config, app.config和appsettings.json
static SafeDictionary<string, string> _appSettings;
public static SafeDictionary<string, string> AppSettings {
get {
if (_appSettings == null)
{
_appSettings = ConfigurationManager.AppSettings
.ToDictionary()
.ToSafe();
BuildAppSettings( JsonAppSettings, "");
}
return _appSettings;
}
}
static SafeDictionary<string, string> _connectionStrings;
public static SafeDictionary<string, string> ConnectionStrings
{
get
{
if (_connectionStrings == null)
{
_connectionStrings = ConfigurationManager.ConnectionStrings
.Cast<ConnectionStringSettings>()
.ToDictionary(x => x.Name, x => x.ConnectionString)
.ToSafe();
foreach (var jp in JsonAppSettings["ConnectionStrings"].Cast<JProperty>())
_connectionStrings.Add(jp.Name, jp.Value.ToString() );
}
return _connectionStrings;
}
}
https://github.com/bitministry/common