咱們先看一下1.x和2.x的程序入口項的一個差別html
public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } }
public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); }
2.x對默認配置進行了簡化,把一些基本配置移動了 CreateDefaultBuilder 方法中 json
public static IWebHostBuilder CreateDefaultBuilder(string[] args) { IWebHostBuilder hostBuilder = new WebHostBuilder()
.UseKestrel((Action<WebHostBuilderContext, KestrelServerOptions>) ((builderContext, options) => options.Configure((IConfiguration) builderContext.Configuration.GetSection("Kestrel"))))
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((Action<WebHostBuilderContext, IConfigurationBuilder>) ((hostingContext, config) => { IHostingEnvironment hostingEnvironment = hostingContext.HostingEnvironment; config.AddJsonFile("appsettings.json", true, true)
.AddJsonFile("appsettings." + hostingEnvironment.EnvironmentName + ".json", true, true); if (hostingEnvironment.IsDevelopment()) { Assembly assembly = Assembly.Load(new AssemblyName(hostingEnvironment.ApplicationName)); if (assembly != (Assembly) null) config.AddUserSecrets(assembly, true); } config.AddEnvironmentVariables(); if (args == null) return; config.AddCommandLine(args); }))
.ConfigureLogging((Action<WebHostBuilderContext, ILoggingBuilder>) ((hostingContext, logging) => { logging.AddConfiguration((IConfiguration) hostingContext.Configuration.GetSection("Logging")); logging.AddConsole(); logging.AddDebug(); }))
.ConfigureServices((Action<WebHostBuilderContext, IServiceCollection>) ((hostingContext, services) => { services.PostConfigure<HostFilteringOptions>((Action<HostFilteringOptions>) (options => { if (options.AllowedHosts != null && options.AllowedHosts.Count != 0) return; string str = hostingContext.Configuration["AllowedHosts"]; string[] strArray1; if (str == null) strArray1 = (string[]) null; else strArray1 = str.Split(new char[1]{ ';' }, StringSplitOptions.RemoveEmptyEntries); string[] strArray2 = strArray1; HostFilteringOptions filteringOptions = options; string[] strArray3; if (strArray2 == null || strArray2.Length == 0) strArray3 = new string[1]{ "*" }; else strArray3 = strArray2; filteringOptions.AllowedHosts = (IList<string>) strArray3; })); services.AddSingleton<IOptionsChangeTokenSource<HostFilteringOptions>>((IOptionsChangeTokenSource<HostFilteringOptions>) new ConfigurationChangeTokenSource<HostFilteringOptions>(hostingContext.Configuration)); services.AddTransient<IStartupFilter, HostFilteringStartupFilter>(); }))
.UseIISIntegration()
.UseDefaultServiceProvider((Action<WebHostBuilderContext, ServiceProviderOptions>) ((context, options) => options.ValidateScopes = context.HostingEnvironment.IsDevelopment())); if (args != null) hostBuilder.UseConfiguration((IConfiguration) new ConfigurationBuilder().AddCommandLine(args).Build()); return hostBuilder; }
這裏咱們能夠看到在CreateDefaultBuilder生成器中,定義了默認使用的Web服務器(UseKestrel,使用的是KestrelServer)和一些基礎的配置,包括文件路徑、應用配置(按appsettings.json,appsettings.{Environment}.json次序加載)、環境變量、日誌,IIS集成等,若是須要的話,還能夠指定其餘類型的Server(IIS HTTP Server,HTTP.sys Server)和自定義Server(繼承IServer)。服務器
返回到Program中,在獲取到了WebHostBuilder以後緊接着就指定了啓動類UseStartup<Startup>(),Build方法是WebHostBuilder最終的目的(在這個方法裏面構建了管道),將構造一個WebHost返回,這裏引出了咱們在ASP.NET Core - 開篇所說的重要對象:WebHost,而且運行它的Run方法用於啓動應用並開始監聽全部到來的HTTP請求。session
Startup方法用來指定應用程序的啓動類,這裏主要有兩個做用:app
public class Startup { private readonly IHostingEnvironment _env; private readonly IConfiguration _config; private readonly ILoggerFactory _loggerFactory; public Startup(IHostingEnvironment env, IConfiguration config, ILoggerFactory loggerFactory) { _env = env; _config = config; _loggerFactory = loggerFactory; } // 注入服務到容器中 public void ConfigureServices(IServiceCollection services) { var logger = _loggerFactory.CreateLogger<Startup>(); if (_env.IsDevelopment()) { // Development service configuration logger.LogInformation("Development environment"); } else { // Non-development service configuration logger.LogInformation($"Environment: {_env.EnvironmentName}"); } ... } // 配置Http請求處理管道 public void Configure(IApplicationBuilder app) { ... } }
Startup 類的 執行順序:構造 -> ConfigureServices -> Configureide
1)Startup Constructor(構造函數)函數
上面的構造函數引出了咱們開篇說的三個重要對象:IHostingEnvironment ,IConfiguration ,ILoggerFactory ,這裏先講構造函數的做用,這些對象後面會分篇講。顯而易見,這裏主要是經過依賴注入實例化了該類中須要用到的對象(根據本身的業務),比較簡單。ui
2) ConfigureServicesspa
首先這個方法是可選的,它的參數是IServiceCollection,這也是咱們開篇說的重要對象,並且是很是重要的對象,這是一個原生的Ioc容器,全部須要用到的服務均可以註冊到裏面,通常是經過約定風格services.Addxxx, 這樣就可讓這些服務在應用和Configure方法使用(用來構建管道)。3d
3)Configure
用於構建管道處理Http請求,管道中的每一箇中間件(Middleware)組件負責請求處理和選擇是否將請求傳遞到管道中的下一個組件,在這裏咱們能夠添加本身想要的中間件來處理每個Http請求,通常是使用上面的ConfigureServices方法中註冊好的服務,通常的用法是 app.Usexxx,這個Usexxx方法是基於IApplicationBuilder的擴展。
須要注意的有三個地方:
public void Configure(IApplicationBuilder app) { if (env.IsDevelopment()) {// Use the Developer Exception Page to report app runtime errors. app.UseDeveloperExceptionPage(); } else {// Enable the Exception Handler Middleware to catch exceptions // thrown in the following middlewares. app.UseExceptionHandler("/Error"); } // Return static files and end the pipeline. app.UseStaticFiles(); // Use Cookie Policy Middleware to conform to EU General Data // Protection Regulation (GDPR) regulations. app.UseCookiePolicy(); // Authenticate before the user accesses secure resources. app.UseAuthentication(); // If the app uses session state, call Session Middleware after Cookie // Policy Middleware and before MVC Middleware. app.UseSession(); // Add MVC to the request pipeline. app.UseMvc(); }
若是你不想使用Startup類的話,可使用如下方式配置本身的服務註冊和管道構建,雖然這種方式有點odd :)
public class Program { public static IHostingEnvironment HostingEnvironment { get; set; } public static IConfiguration Configuration { get; set; } public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { }) .ConfigureServices(services => { ... }) .Configure(app => { var loggerFactory = app.ApplicationServices .GetRequiredService<ILoggerFactory>(); var logger = loggerFactory.CreateLogger<Program>(); var env = app.ApplicationServices.GetRequiredServices<IHostingEnvironment>(); var config = app.ApplicationServices.GetRequiredServices<IConfiguration>(); logger.LogInformation("Logged in Configure"); if (env.IsDevelopment()) { ... } else { ... } var configValue = config["subsection:suboption1"]; ... }); }
這裏須要注意的是,Startup只是一個概念,類的名字是能夠任意的,只須要在啓動項UseStartup中指定你這個啓動類便可。
正如ASP.NET Core - 開篇所說的,一個ASP.NET Core應用其實就是一個控制檯應用程序,它在應用啓動時構建一個 Web 服務器,而且經過指定的Startup類來構建應用服務和請求管道,進而監聽和處理全部的Http請求。