在 C# Asp.net Core 中,IApplicationBuilder.Use() 和 IApplicationBuilder.Run() 之间有什么区别?
我们可以在 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){
//configure middleware using IApplicationBuilder here..
app.Run(async (context) =>{
await context.Response.WriteAsync("Hello World!");
});
// other code removed for clarity..
}
}上面的 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");
});
// the following will never be executed
app.Run(async (context) =>{
await context.Response.WriteAsync(" 2nd Middleware");
});
}USE
要配置多个中间件,请使用 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");
});
}
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP