如何处理ASP.NET 5 AppSettings中的属性层次结构?

时间:2015-06-28 01:15:43

标签: c# asp.net-core asp.net-core-mvc

在ASP.NET 4中组织设置,我在设置键前面加上一个小字,指示此配置的使用位置(例如key =“dms:url”,“sms:fromNumber”.... etc)

在ASP.NET 5中,AppSettings配置映射到强类型类。 我需要为“dms:url”构建什么属性?怎么可能映射破折号和& ASP.NET 5中C#属性的特殊字符?

1 个答案:

答案 0 :(得分:2)

您可以在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; }
}

然后,我们将配置加载到IConfigurationSourceRoot的实例中,然后使用GetSubKey设置AppSettings的值。最佳做法是在ConfigureServices中执行此操作并将其添加到DI Container。

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;
    }

如果你想保持一切平整并使用像你一直在做的伪层次结构,你可以,但“:”不是变量名的有效符号。您需要使用有效的符号,例如“_”或“ - ”。