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

How to handle a hierarchy of properties in ASP.NET 5 AppSettings?

在 ASP.NET 4 中组织设置,我在设置键前加上一个小词,指示使用此配置的位置(例如 key="dms:url"、"sms:fromNumber" .. ..等)。

在ASP.NET5中,AppSettings配置映射到强类型class。 我需要为 "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 class。

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 容器。

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

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