asp.net-core - WebHost 从 appsettings.json 读取哪些值

标签 asp.net-core .net-core self-hosting

在 .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 documentationCreateDefaultBuilder ...

  • 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/

相关文章:

c# - 如何在 ASP.Net Core 中使用 Google.Protobuf.WellknownTypes.Struct

c# - 文件夹未复制到输出目录

authentication - 如何处理部署在 Kestrel 上的 asp.net core mvc 中的 windows 身份验证弹出窗口的取消按钮?

oauth - 在 owin 自托管进程之间共享 key

asp.net-mvc - 使用 asp.net 属性路由的根路径的默认路由

asp.net-core - User.Claims.FirstOrDefault().Value 在登录操作中为空(ASP.NET Identity 3)?

c# - Blazor 中如何通过 @Ref 获取的引用设置组件属性

asp.net-core - ASP.NET Core 6.0 最小 API/Swagger 标签

asp.net-core - 如何在 Entity Framework Core 中获取映射实体的表名称

ios - 如何将自托管内容与交易相关联?