我们可以在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..
}
}
上面的 MyMiddleware 函数不是异步的,因此会阻塞线程 直到它完成执行为止。因此,通过使用async和 等待以提高性能和可伸缩性。
'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");
});
}