02 Web Host 的默认配置.mp4 (60.69MB)```csharp public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup();

  1. WebHostBuilder 知道该如何配置 Web Server 的环境,CreateDefaultBuilder 即进行默认配置。
  2. <a name="c51efb73"></a>
  3. # 默认配置
  4. 反编译的 CreateDefaultBuilder 方法源码:
  5. ```csharp
  6. /// <summary>
  7. /// Initializes a new instance of the <see cref="T:Microsoft.AspNetCore.Hosting.WebHostBuilder" /> class with pre-configured defaults.
  8. /// </summary>
  9. public static IWebHostBuilder CreateDefaultBuilder(string[] args)
  10. {
  11. WebHostBuilder hostBuilder = new WebHostBuilder();
  12. if (string.IsNullOrEmpty(hostBuilder.GetSetting(WebHostDefaults.ContentRootKey)))
  13. hostBuilder.UseContentRoot(Directory.GetCurrentDirectory());
  14. if (args != null)
  15. hostBuilder.UseConfiguration((IConfiguration) new ConfigurationBuilder().AddCommandLine(args).Build());
  16. hostBuilder.UseKestrel((Action<WebHostBuilderContext, KestrelServerOptions>) ((builderContext, options) => options.Configure((IConfiguration) builderContext.Configuration.GetSection("Kestrel")))).ConfigureAppConfiguration((Action<WebHostBuilderContext, IConfigurationBuilder>) ((hostingContext, config) =>
  17. {
  18. IHostingEnvironment hostingEnvironment = hostingContext.HostingEnvironment;
  19. config.AddJsonFile("appsettings.json", true, true).AddJsonFile("appsettings." + hostingEnvironment.EnvironmentName + ".json", true, true);
  20. if (hostingEnvironment.IsDevelopment())
  21. {
  22. Assembly assembly = Assembly.Load(new AssemblyName(hostingEnvironment.ApplicationName));
  23. if (assembly != (Assembly) null)
  24. config.AddUserSecrets(assembly, true);
  25. }
  26. config.AddEnvironmentVariables();
  27. if (args == null)
  28. return;
  29. config.AddCommandLine(args);
  30. })).ConfigureLogging((Action<WebHostBuilderContext, ILoggingBuilder>) ((hostingContext, logging) =>
  31. {
  32. logging.AddConfiguration((IConfiguration) hostingContext.Configuration.GetSection("Logging"));
  33. logging.AddConsole();
  34. logging.AddDebug();
  35. logging.AddEventSourceLogger();
  36. })).ConfigureServices((Action<WebHostBuilderContext, IServiceCollection>) ((hostingContext, services) =>
  37. {
  38. services.PostConfigure<HostFilteringOptions>((Action<HostFilteringOptions>) (options =>
  39. {
  40. if (options.AllowedHosts != null && options.AllowedHosts.Count != 0)
  41. return;
  42. string str = hostingContext.Configuration["AllowedHosts"];
  43. string[] strArray1;
  44. if (str == null)
  45. {
  46. strArray1 = (string[]) null;
  47. }
  48. else
  49. {
  50. char[] separator = new char[1]{ ';' };
  51. int num = 1;
  52. strArray1 = str.Split(separator, (StringSplitOptions) num);
  53. }
  54. string[] strArray2 = strArray1;
  55. HostFilteringOptions filteringOptions = options;
  56. string[] strArray3;
  57. if (strArray2 == null || strArray2.Length == 0)
  58. strArray3 = new string[1]{ "*" };
  59. else
  60. strArray3 = strArray2;
  61. filteringOptions.AllowedHosts = (IList<string>) strArray3;
  62. }));
  63. services.AddSingleton<IOptionsChangeTokenSource<HostFilteringOptions>>((IOptionsChangeTokenSource<HostFilteringOptions>) new ConfigurationChangeTokenSource<HostFilteringOptions>(hostingContext.Configuration));
  64. services.AddTransient<IStartupFilter, HostFilteringStartupFilter>();
  65. })).UseIIS().UseIISIntegration().UseDefaultServiceProvider((Action<WebHostBuilderContext, ServiceProviderOptions>) ((context, options) => options.ValidateScopes = context.HostingEnvironment.IsDevelopment()));
  66. return (IWebHostBuilder) hostBuilder;
  67. }
  • 使用 Kestrel Web Server
    • ASP.NET Core 内置,跨平台
  • IIS 集成
    • UseIIS(), UseIISIntegration()
  • Log
  • IConfiguration 接口

    IConfiguration 配置信息的来源

    上面源码第一句 WebHostBuilder hostBuilder = new WebHostBuilder(); 创建 WebHostBuilder 对象时,就初始化了 Configuration(先配置 _config 字段,然后将值传入新建的 WebHostBuilderContext):

    1. /// <summary>
    2. /// Initializes a new instance of the <see cref="T:Microsoft.AspNetCore.Hosting.WebHostBuilder" /> class.
    3. /// </summary>
    4. public WebHostBuilder()
    5. {
    6. this._hostingEnvironment = new HostingEnvironment();
    7. this._configureServicesDelegates = new List<Action<WebHostBuilderContext, IServiceCollection>>();
    8. this._configureAppConfigurationBuilderDelegates = new List<Action<WebHostBuilderContext, IConfigurationBuilder>>();
    9. this._config = (IConfiguration) new ConfigurationBuilder().AddEnvironmentVariables("ASPNETCORE_").Build();
    10. if (string.IsNullOrEmpty(this.GetSetting(WebHostDefaults.EnvironmentKey)))
    11. this.UseSetting(WebHostDefaults.EnvironmentKey, Environment.GetEnvironmentVariable("Hosting:Environment") ?? Environment.GetEnvironmentVariable("ASPNET_ENV"));
    12. if (string.IsNullOrEmpty(this.GetSetting(WebHostDefaults.ServerUrlsKey)))
    13. this.UseSetting(WebHostDefaults.ServerUrlsKey, Environment.GetEnvironmentVariable("ASPNETCORE_SERVER.URLS"));
    14. this._context = new WebHostBuilderContext()
    15. {
    16. Configuration = this._config
    17. };
    18. }

    配置信息来源:

  • appsettings.json

  • User Secrets
  • 系统环境变量
  • 命令行参数
    1. config.AddJsonFile("appsettings.json", true, true)
    2. .AddJsonFile("appsettings." + hostingEnvironment.EnvironmentName + ".json", true, true);
    3. if (hostingEnvironment.IsDevelopment())
    4. {
    5. Assembly assembly = Assembly.Load(new AssemblyName(hostingEnvironment.ApplicationName));
    6. if (assembly != (Assembly) null)
    7. config.AddUserSecrets(assembly, true);
    8. }
    9. config.AddEnvironmentVariables();
    10. if (args == null)
    11. return;
    12. config.AddCommandLine(args);
    如果出现重复的属性,后添加的会覆盖前面的值,所以系统环境变量的优先级高于 appsettings.json。