在 .Net Core 中,您可以使用 WebHost
自托管 Web 服务器.有一个方法叫CreateDefaultBuilder()
,其中 Microsoft documentation声明如下:
CreateDefaultBuilder
performs the following tasks:
- Loads app configuration from:
- appsettings.json.
但是,似乎没有关于您可以将哪些参数放入
appsettings.json
的任何文档。拥有 WebHost
自动获取默认值以外的配置值。例如,我尝试将以下内容添加到我的
appsettings.json
,但服务器以 http://localhost:5000
启动不管:{
"Kestrel" : {
"urls" : "http://*:8080"
},
"server" : {
"urls" : "http://*:8080"
}
}
我知道我可以阅读 appsettings.json
我自己使用 ConfigurationBuilder
,但这有点违背了文档的目的那么,我需要在我的
appsettings.json
中放入什么?文件有 CreateDefaultBuilder()
不使用默认值?要放入 appsettings.json
的所有可能值的列表也将受到欢迎。
最佳答案
为什么 CreateDefaultBuilder 不使用 appsettings.json 值配置主机?
部分答案是区分主机和应用程序配置。 The documentation说 CreateDefaultBuilder
...
- Loads host configuration from:
- Environment variables prefixed with ASPNETCORE_ ...
- Command-line arguments.
- Loads app configuration from:
- appsettings.json.
- appsettings.{Environment}.json.
从内部
CreateDefaultBuilder
,原因是appsettings.json
不会自动影响主机,是那些设置正在配置应用程序,而应用程序配置不会影响主机配置。文档表明,当它说:
IWebHostBuilder
configuration is added to the app's configuration, but the converse isn't true —ConfigureAppConfiguration
doesn't affect the IWebHostBuilder configuration.
看着source code显示
CreateDefaultBuilder
方法只添加 appsettings.json
来自其对 ConfigureAppConfiguration
的调用中的值.这就是为什么这些值不会自动影响主机的原因。我们如何使用 *.json 文件中的值配置主机?
CreateDefaultBuilder
不会使用 *.json
自动配置主机文件。我们需要手动完成,the documentation specifies how .在示例中,文件名为 hostsettings.json
,并且该示例像这样显式添加它:var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("hostsettings.json")
.Build();
return WebHost.CreateDefaultBuilder(args)
// this impacts *both* host and app config
.UseConfiguration(config)
.UseStartup<Startup>();
名字没有魔力
hostsettings.json
.事实上,我们可以将我们的主机设置和我们的应用程序设置合并到一个名为 appsettings.json
的文件中。 .方式CreateDefaultBuilder
作品鼓励我们将这些设置分开。我们可以在 *.json 文件中放入哪些 key 来配置主机?
这是list of keys我们可以用来配置主机:
"applicationName"
"startupAssembly"
"hostingStartupAssemblies"
"hostingStartupExcludeAssemblies"
"detailedErrors"
"environment"
"webroot"
"captureStartupErrors"
"urls"
"contentRoot"
"preferHostingUrls"
"preventHostingStartup"
"suppressStatusMessages"
"shutdownTimeoutSeconds"
关于asp.net-core - WebHost 从 appsettings.json 读取哪些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52021335/