C# Asp.net Core 中的 IApplicationBuilder.Use() 和 IApplicationBuilder.Run() 有什么区别?
csharpserver side programmingprogramming更新于 2025/9/30 14:07:17
我们可以在 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);
示例
public class Startup{
public Startup(){
}
public void configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory){
//在此处使用 IApplicationBuilder 配置中间件。
app.Run(async (context) => {
await context.Response.WriteAsync(&"Hello World!");
});
// 为清晰起见,其他代码已删除。
}
}
上述 MyMiddleware 函数不是异步的,因此会阻塞线程直到其执行完成。因此,请使用 async 和 await 将其变为异步函数,以提高性能和可扩展性。
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");
});
// 以下代码永远不会执行
app.Run(async (context) =>{
await context.Response.WriteAsync(" 第二个中间件");
});
}
使用
要配置多个中间件,请使用 Use() 扩展方法。它与 Run() 方法类似,只是它包含 next 参数,用于按顺序调用下一个中间件。
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");
});
}

