我們可以在Startup類別的Configure方法中設定中間件,使用 IApplicationBuilder實例。
Run()是IApplicationBuilder實例上的擴充方法,它加入了一個終端
將中間件加入應用程式的請求管道。
Run方法是IApplicationBuilder的擴充方法,並接受一個
RequestDelegate的參數。
Run方法的簽章##
public static void Run(this IApplicationBuilder app, RequestDelegate handler)
RequestDelegate的簽章
public delegate Task RequestDelegate(HttpContext context);Example
public class Startup{ public Startup(){ } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory){ //configure middleware using IApplicationBuilder here.. app.Run(async (context) =>{ await context.Response.WriteAsync("Hello World!"); }); // other code removed for clarity.. } }
public class Startup{ public Startup(){ } public void Configure(IApplicationBuilder app, IHostingEnvironment env){ app.Run(MyMiddleware); } private async Task MyMiddleware(HttpContext context){ await context.Response.WriteAsync("Hello World! "); } }
使用Run()配置多個中間件
以下程式碼將始終執行第一個Run方法,並且永遠不會到達第二個Run方法
public void Configure(IApplicationBuilder app, IHostingEnvironment env){ app.Run(async (context) =>{ await context.Response.WriteAsync("1st Middleware"); }); // the following will never be executed app.Run(async (context) =>{ await context.Response.WriteAsync(" 2nd Middleware"); }); }USE要設定多個中間件,請使用 Use() 擴充方法。它類似於 Run() 方法,不同之處在於它包含下一個參數來呼叫下一個中間件 序列
public void Configure(IApplicationBuilder app, IHostingEnvironment env){ app.Use(async (context, next) =>{ await context.Response.WriteAsync("1st Middleware!"); await next(); }); app.Run(async (context) =>{ await context.Response.WriteAsync("2nd Middleware"); }); }
以上是IApplicationBuilder.Use() 與 IApplicationBuilder.Run() C# Asp.net Core 有什麼不同?的詳細內容。更多資訊請關注PHP中文網其他相關文章!