WebHost 从 appsettings.json 读取哪些值

2024-05-02

在 .Net Core 中,您可以使用以下方式自行托管 Web 服务器WebHost。有一种方法叫做CreateDefaultBuilder(),其中微软文档 https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/web-host?view=aspnetcore-2.1陈述如下:

CreateDefaultBuilder执行以下任务:

  • 从以下位置加载应用程序配置:
  • 应用程序设置.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 值配置主机?

部分答案是区分主机和应用程序配置。文档 https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/web-host?view=aspnetcore-2.1#set-up-a-hostCreateDefaultBuilder...

  • Loads host configuration from:
    • 以 ASPNETCORE_ ... 为前缀的环境变量
    • 命令行参数。
  • Loads app configuration from:
    • 应用程序设置.json。
    • appsettings.{环境}.json。

从内部CreateDefaultBuilder,原因是appsettings.json不会自动影响主机,因为这些设置正在配置应用程序,并且应用程序配置不会影响主机配置。该文档表明,当它说:

IWebHostBuilder配置已添加到应用程序的配置中,但反之则不然 —ConfigureAppConfiguration不影响 IWebHostBuilder 配置。

看着源代码 https://github.com/aspnet/MetaPackages/blob/67959ad853947d6ffef1916d02979753c0fd59e3/src/Microsoft.AspNetCore/WebHost.cs#L169-L170表明CreateDefaultBuilder方法仅添加appsettings.json其调用中的值ConfigureAppConfiguration。这就是为什么这些值不会自动影响主机。

我们如何使用 *.json 文件中的值配置主机?

CreateDefaultBuilder不会自动配置主机*.json文件。我们需要手动执行此操作,并且该文档指定了如何 https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/web-host?view=aspnetcore-2.1#override-configuration。在示例中,文件名为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。道路CreateDefaultBuilderWorks 鼓励我们将这些设置保持一定程度的独立。

我们可以在 *.json 文件中放入哪些密钥来配置主机?

这是键列表 https://github.com/aspnet/Hosting/blob/master/src/Microsoft.AspNetCore.Hosting.Abstractions/WebHostDefaults.cs我们可以用它来配置主机:

"applicationName"
"startupAssembly"
"hostingStartupAssemblies"
"hostingStartupExcludeAssemblies"
"detailedErrors"
"environment"
"webroot"
"captureStartupErrors"
"urls"
"contentRoot"
"preferHostingUrls"
"preventHostingStartup"
"suppressStatusMessages"
"shutdownTimeoutSeconds"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

WebHost 从 appsettings.json 读取哪些值 的相关文章

随机推荐