public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); }
CreateDefaultBuilder
web
public static IWebHostBuilder CreateDefaultBuilder(string[] args) { var builder = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .ConfigureAppConfiguration((hostingContext, config) => { var env = hostingContext.HostingEnvironment; config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); if (env.IsDevelopment()) { var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName)); if (appAssembly != null) { config.AddUserSecrets(appAssembly, optional: true); } } config.AddEnvironmentVariables(); if (args != null) { config.AddCommandLine(args); } }) .ConfigureLogging((hostingContext, logging) => { logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); logging.AddConsole(); logging.AddDebug(); }) .UseIISIntegration() .UseDefaultServiceProvider((context, options) => { options.ValidateScopes = context.HostingEnvironment.IsDevelopment(); }); return builder; }
請求管道: 那些處理http requests並返回responses的代碼組成了request pipeline(請求管道).json
中間件: 咱們可使用一些程序來配置請求管道(request pipeline)以便處理requests和responses. 好比處理驗證(authentication)的程序, MVC自己就是個中間件(middleware).安全
當接收到一個請求時,請求會交給中間件構成的中間件管道進行處理,管道就是多箇中間件構成,請求從一箇中間件的一端進入,從中間件的另外一端出來,每一箇中間件均可以對HttpContext請求開始和結束進行處理.服務器
本身寫一箇中間件測試下:mvc
經過約定方法實現:app
public class Floor1Middleware { private readonly RequestDelegate _next; public Floor1Middleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { Console.WriteLine("Floor1Middleware In"); //Do Something //To FloorTwoMiddleware await _next(context); //Do Something Console.WriteLine("Floor1Middleware Out"); } }
添加擴展方法:async
public static class Floor1MiddlewareExtensions { public static IApplicationBuilder UseFloor1Middleware(this IApplicationBuilder builder) { return builder.UseMiddleware<Floor1Middleware>(); } }
經過 IMiddleware 實現ide
public class Floor3Middleware : IMiddleware { public async Task InvokeAsync(HttpContext context, RequestDelegate next) { Console.WriteLine("Floor3Middleware In"); //Do Something //To FloorTwoMiddleware await next(context); //Do Something Console.WriteLine("Floor3Middleware Out"); } }
public static class MiddlewareExtensions { public static IApplicationBuilder UseFloor3Middleware( this IApplicationBuilder builder) { return builder.UseMiddleware<Floor3Middleware>(); } }
public void ConfigureServices(IServiceCollection services) { services.AddTransient<Floor3Middleware>(); services.AddMvc(); }
也能夠用簡要的寫法,直接在Startup的Configure方法中這樣寫:測試
app.Use(async (context, next) => { Console.WriteLine("Floor2Middleware In"); await next.Invoke(); Console.WriteLine("Floor2Middleware Out"); });
測試中間件:
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseFloor1Middleware(); app.Use(async (context, next) => { Console.WriteLine("Floor2Middleware In"); await next.Invoke(); Console.WriteLine("Floor2Middleware Out"); }); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
運行查看輸出爲:
DIDemo> Floor1Middleware In DIDemo> Floor2Middleware In DIDemo> Floor3Middleware In DIDemo> info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1] DIDemo> Route matched with {action = "Index", controller = "Home"}. Executing action DIDemo.Controllers.HomeController.Index (DIDemo) DIDemo> info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1] DIDemo> Executing action method DIDemo.Controllers.HomeController.Index (DIDemo) - Validation state: Valid DIDemo> info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2] DIDemo> Executed action method DIDemo.Controllers.HomeController.Index (DIDemo), returned result Microsoft.AspNetCore.Mvc.ViewResult in 0.1167ms. DIDemo> info: Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor[1] DIDemo> Executing ViewResult, running view Index. DIDemo> info: Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor[4] DIDemo> Executed ViewResult - view Index executed in 3.3508ms. DIDemo> info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2] DIDemo> Executed action DIDemo.Controllers.HomeController.Index (DIDemo) in 9.5638ms DIDemo> Floor3Middleware Out DIDemo> Floor2Middleware Out DIDemo> Floor1Middleware Out