1
在ASP.NET 4中组织设置,我在设置密钥前添加一个小字,指示使用此配置的位置(例如key =“dms:url”,“sms:fromNumber”....等)。如何处理ASP.NET 5 AppSettings中的属性层次结构?
在ASP.NET 5中,AppSettings配置映射到强类型类。 什么是我需要为“dms:url”构建的属性?如何将特殊字符&映射为ASP.NET 5中的C#属性?
在ASP.NET 4中组织设置,我在设置密钥前添加一个小字,指示使用此配置的位置(例如key =“dms:url”,“sms:fromNumber”....等)。如何处理ASP.NET 5 AppSettings中的属性层次结构?
在ASP.NET 5中,AppSettings配置映射到强类型类。 什么是我需要为“dms:url”构建的属性?如何将特殊字符&映射为ASP.NET 5中的C#属性?
您可以在config.json
{
"AppSettings": {
"SiteTitle": "PresentationDemo.Web",
"Dms": {
"Url": "http://google.com",
"MaxRetries": "5"
},
"Sms": {
"FromNumber": "5551234567",
"APIKey": "fhjkhededeudoiewueoi"
}
},
"Data": {
"DefaultConnection": {
"ConnectionString": "MyConnectionStringHere. Included to show you can use the same config file to process both strongly typed and directly referenced values"
}
}
}
我们定义的AppSettings为POCO类层次结构中组织您的配置文件。
public class AppSettings
{
public AppSettings()
{
Dms = new Dms(); // need to instantiate (Configuration only sets properties not create the object)
Sms = new Sms(); // same
}
public string SiteTitle { get; set; }
public Dms Dms { get; set; }
public Sms Sms { get; set; }
}
public class Dms
{
public string Url { get; set; }
public int MaxRetries { get; set; }
}
public class Sms
{
public string FromNumber { get; set; }
public string ApiKey { get; set; }
}
我们然后加载配置成使用GetSubKey的AppSettings的IConfigurationSourceRoot
,然后设定值的实例。最佳做法是在ConfigureServices中执行此操作并将其添加到DI容器中。
public class Startup
{
public Startup(IHostingEnvironment env)
{
// Setup configuration sources.
var configuration = new Configuration()
.AddJsonFile("config.json")
.AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);
}
public void ConfigureServices(IServiceCollection services)
{
// Add Application settings to the services container.
services.Configure<AppSettings>(Configuration.GetSubKey("AppSettings"));
//Notice we can also reference elements directly from Configuration using : notation
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
}
}
我们现在可以通过构造函数在控制器中提供访问权限。我设定的设定值明确的构造函数,但如果你想保留一切平整,使用伪层次就像你一直在做,你可以使用整个IOptions
public class HomeController : Controller
{
private string _title;
private string _fromNumber;
private int _maxRetries;
public HomeController(IOptions<AppSettings> settings)
{
_title = settings.Options.SiteTitle;
_fromNumber = settings.Options.Sms.FromNumber;
_maxRetries = settings.Options.Dms.MaxRetries;
}
,你可以,但“:”是不是变量名的有效符号。您需要使用有效的符号,如“_”或“ - ”。
Hi @ gerald-davis,看起来我需要在Startup.cs中重新配置一些东西 你能指导我吗? 我的意思是: var appSettingsConfig = services.Configure(Configuration.GetSubKey(“AppSettings”)); 将是不够的!对?! 我得到了对象引用异常,因为AppSettings中的Dms属性为null。 我创建了Dms类,然后在AppSettings类中创建了一个名为Dms的属性。 –
bunjeeb
使用上面的配置文件没有AppSetting的Dms属性。使用上面的配置文件将以AppSettings.Options.Dms.FromNumber为例。请注意属性链中的“选项”。我通过手机回应。当我到达工作站时,我将更新startup.cs中的初始化代码(除非其他人)。 –
谢谢你的回复,等待你的答案..因为我找不到有用的博客文章解释..也许如果你知道一些资源,请发送给我。 – bunjeeb