如何从根目录获取强类型配置?

How can you get strongly-typed config from the root?

在 ASP .NET 5 中,您可以将应用程序设置映射到 class。有关最新示例,请参阅

我看到的执行此操作的代码通常如下所示:

services.Configure<AppSettings>(Configuration.GetConfigurationSection("AppSettings"));

因此,您的 appsettings.json 中应该有一个具有该名称的节点(本文中的示例):

{
    "AppSettings" : {
        "SiteTitle" :  "My Web Site"
    },
    "Data": {
        "DefaultConnection": {
            "ConnectionString": "Server=(localdb)\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;"
        }
    }
}

是否可以获取整个文件(从根目录)而不是像 AppSettings 这样必须声明一个节点?

是的,你可以。使用 ConfigurationBinder

 var configurationBuilder = new ConfigurationBuilder();
 // Add the providers that you want here

 var config = configurationBuilder.Build();

 var options = new StrongTypeObject();
 config.Bind(options);

更多示例:https://github.com/aspnet/Configuration/blob/dev/test/Microsoft.Extensions.Configuration.Binder.Test/ConfigurationBinderTests.cs