ASP.NET Run
最后修改于 2025 年 4 月 3 日
在本文中,我们将探讨 ASP.NET 8 中的 Run 方法。此方法对于启动应用程序和处理 ASP.NET 管道中的 HTTP 请求至关重要。
ASP.NET 是一个跨平台、高性能的框架,用于构建现代 Web 应用程序。Run 方法是配置请求管道的最后一步。
基本定义
ASP.NET 中的 Run 方法是一个扩展方法,它将一个终止中间件添加到应用程序的请求管道中。它处理到达它的所有请求。
与其他中间件组件不同,Run 没有 next 参数。这意味着它是管道的最后一步,不会调用后续中间件。
Run 通常在中间件链的末尾使用,以处理未被先前中间件处理的请求。它通常用于简单的应用程序。
ASP.NET Run 示例
以下示例演示了在 ASP.NET 应用程序中使用 Run 的基本用法。
Program.cs
var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.Use(async (context, next) => { await context.Response.WriteAsync("Middleware 1 processing...\n"); await next(); }); app.Run(async context => { await context.Response.WriteAsync("Terminal middleware handling request\n"); await context.Response.WriteAsync($"Request path: {context.Request.Path}\n"); }); app.Run();
此示例展示了一个简单的 ASP.NET 应用程序,其中包含两个中间件组件。第一个中间件写入一条消息并调用链中的下一个中间件。
Run 中间件是终止性的 - 它写入一条消息和请求路径到响应中。对于匹配的请求,Run 之后的任何中间件都不会执行。
最终的 app.Run()
启动应用程序并开始监听传入的 HTTP 请求。这与中间件 Run 方法不同。
这是另一个示例,展示了如何使用 Run 来处理特定路由
Program.cs
var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.Map("/hello", helloApp => { helloApp.Run(async context => { await context.Response.WriteAsync("Hello from the /hello route!\n"); }); }); app.Map("/time", timeApp => { timeApp.Run(async context => { await context.Response.WriteAsync($"Current time: {DateTime.Now}\n"); }); }); app.Run(async context => { context.Response.StatusCode = 404; await context.Response.WriteAsync("Not found. Try /hello or /time\n"); }); app.Run();
此示例使用 Map with Run 演示了特定于路由的终止中间件。每个映射的路由都有自己的终止中间件来处理请求。
最终的 Run 中间件充当未匹配路由的“catch-all”,返回 404 状态。这种模式对于没有控制器的简单应用程序很有用。
来源
在本文中,我们探讨了 ASP.NET 8 中的 Run 方法。这个重要的组件有助于在 ASP.NET 应用程序中构建请求处理管道。