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

本文关键字:处理 属性 层次结构 AppSettings ASP NET | 更新日期: 2023-09-27 18:00:20

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

在ASP.NET 5中,AppSettings配置被映射到一个强类型类。我需要为"dms:url"构建什么属性?如何映射破折号&ASP.NET 5中C#属性的特殊字符?

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

您可以在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容器中。

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

如果你想像以前一样保持一切平坦并使用伪层次结构,你可以,但":"不是变量名的有效符号。您需要使用诸如"_"或"-"之类的有效符号。