Visual

02 Web Host 的默认配置.mp4 (60.69MB)

  1. public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
  2. WebHost.CreateDefaultBuilder(args)
  3. .UseStartup<Startup>();

WebHostBuilder 知道该如何配置 Web Server 的环境,CreateDefaultBuilder 即进行默认配置。

默认配置

反编译的 CreateDefaultBuilder 方法源码:

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