我们可以在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方法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 之间有什么区别?的详细内容,更多请关注编程之家其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。