practical-aspnetcore 端点路由(Endpoint Routing)实战指南:32 个可运行示例深度解析

原创2026-10-14 19:14:111,717 阅读
文章标签:示例工程

practical-aspnetcore 端点路由(Endpoint Routing)实战指南:32 个可运行示例深度解析

导读

本文围绕 projects/endpoint-routing/README.md 展开,系统梳理 ASP.NET Core 从 3.0 引入的端点路由(Endpoint Routing)机制在 practical-aspnetcore 仓库中的 32 个可运行示例,覆盖端点映射、回退路由、元数据(Metadata)读取、Host 匹配、动态路由、Area、认证授权与参数转换器(Parameter Transformer)等核心主题。读者学完后,将能根据实际场景精确选用 MapGet、MapRazorPages、MapControllers、MapFallbackToFile、MapDynamicControllerRoute 等 API,并理解 HttpContext.GetEndpoint() 与 Endpoint.Metadata 在中间件中的底层工作原理。

Endpoint Routing 概述与示例索引

端点路由是 ASP.NET Core 3.0 引入的路由模型,它将"路由匹配"与"端点执行"解耦:UseRouting 负责根据请求匹配出对应的 Endpoint,UseEndpoints(在现代模板中由 Map* 系列扩展方法代替)负责把端点注册进路由表。相比旧版路由,它更可控、性能更好,并让中间件与端点之间可以交换元数据。

本仓库的 projects/endpoint-routing 目录集中存放了 32 个演示目录(new-routing 至 new-routing-31 以及 parameter-transformer),另有 endpoint-routing 至 endpoint-routing-6 几个关于 LinkGenerator 的补充示例。所有示例的 .csproj 均以 Microsoft.NET.Sdk.Web 为 SDK、目标框架为 net10.0(见 new-routing.csproj),使用顶层语句(top-level statements)编写,可直接 dotnet run 运行。

端点映射基础:Razor Pages 与 MVC

只启用 Razor Pages(new-routing)

new-routing/Program.cs 演示了最简形态——应用只映射 Razor Pages,不包含任何 MVC 控制器路由:

var builder = WebApplication.CreateBuilder();
builder.Services.AddRazorPages();

var app = builder.Build();
app.MapRazorPages();
app.Run();

app.MapRazorPages() 本质上是 IEndpointRouteBuilder 的扩展方法,把每个带有 @page 指令的 .cshtml 页面注册为端点。在该示例中,MVC 控制器完全不可用(其 README.md 明确注明 "MVC Controllers won't work at all in this sample")。

只启用 MVC(new-routing-2)

new-routing-2/Program.cs 仅注册 MVC 控制器:

var builder = WebApplication.CreateBuilder();
builder.Services.AddControllersWithViews();

var app = builder.Build();
app.MapControllers();
app.Run();

[Route("")]
public class HomeController : Controller
{
    public IActionResult Index() => Content("Hello World. Razor Pages won't work in this sample.");
}

注意这里使用的是属性路由(attribute routing),[Route("")] 显式声明在控制器上;README 强调该示例"只映射 MVC 属性路由,不使用约定路由(convention routing)"。

MVC + 默认约定路由(new-routing-3)

new-routing-3/Program.cs 通过 app.MapDefaultControllerRoute() 启用经典的默认约定路由:

app.MapDefaultControllerRoute();

MapDefaultControllerRoute 内部等价于注册 {controller=Home}/{action=Index}/{id?} 这条默认路由模板,即省略控制器、动作或 id 时分别回退到 Home、Index 与空值。它约等于 README 中描述的"带默认 {controller=Home}/{action=Index}/{id?} 的 MVC 路由映射"。

直接使用 RequestDelegate 构建极简 Web 服务

MapGet / MapPost / MapPut / MapDelete(new-routing-4)

new-routing-4/Program.cs 展示了不用控制器、不用页面,直接用 RequestDelegate 处理 HTTP 请求的极简服务:

var app = WebApplication.Create();
app.MapGet("/", async context =>
{
    await context.Response.WriteAsync("Hello world");
});
app.Run();

MapGet 会把匹配 GET / 的请求交给传入的委托(其签名即 RequestDelegate)。README 指出 MapPost、MapPut、MapDelete 同样可用,这一 API 组合"允许创建非常极简的 Web 服务应用"("This allow the creation of very minimalistic web services apps")。

Map 通配映射(new-routing-5)

new-routing-5/Program.cs 使用 Map 注册不限定 HTTP 动词的端点,委托内自行判断请求方法:

app.Map("/", async context =>
{
    if (context.Request.Method == "GET")
        await context.Response.WriteAsync("Hello world");
});

MapMethods 按 HTTP 动词过滤(new-routing-7)

new-routing-7/Program.cs 演示 MapMethods:它可以接收一个或多个 HTTP 动词组成的数组,对请求做动词级过滤:

app.MapMethods("", new[] { "GET" }, async context => { /* ... */ });
app.MapMethods("about", new[] { "POST" }, async context => { /* ... */ });

示例中根路径只响应 GET、/about 只响应 POST——README 说明这是"基于一个或多个 HTTP 动词过滤请求"("filter request based on one or more HTTP verbs")的用法。

端点自省:列出与检视全部端点(new-routing-6)

new-routing-6/Program.cs 演示如何枚举应用中注册的所有端点。它把 WebApplication 强转为 IEndpointRouteBuilder,遍历其 DataSources 属性:

var route = app as IEndpointRouteBuilder;
foreach (EndpointDataSource x in route.DataSources)
{
    foreach (RouteEndpoint e in x.Endpoints)
    {
        await context.Response.WriteAsync($"Display Name: {e.DisplayName}\n");
        await context.Response.WriteAsync($"Route Pattern: {e.RoutePattern.RawText}\n");
        await context.Response.WriteAsync($"Metadata Count: {e.Metadata.Count}\n");
        foreach (var mm in e.Metadata)
        {
            await context.Response.WriteAsync($"Metadata: {mm}\n");
        }
    }
}

EndpointDataSource 是端点路由的核心抽象:每个数据源(MVC、Razor Pages、MapGet 注册的普通端点等)向路由表贡献一批 RouteEndpoint。每个端点可被检视的信息包括 DisplayName、RoutePattern.RawText(原始路由模板文本)以及完整的 Metadata 集合。这个"端点自省"技巧常用于开发期的路由调试。

回退路由(Fallback):未匹配请求的兜底方案

回退到静态文件(new-routing-8)

new-routing-8/Program.cs 用 MapFallbackToFile 让所有未匹配请求返回一个静态页面:

app.MapGet("/contact/us", async context =>
{
    await context.Response.WriteAsync("Contact Us");
});

app.MapFallbackToFile("index.html", new StaticFileOptions()
{
    FileProvider = new PhysicalFileProvider(Path.Combine(app.Environment.ContentRootPath, "static")),
});

这里把静态文件提供程序指向了自定义的 static 目录(对应 static/index.html)。当请求 /contact/us 之外、无法匹配任何路由的 URL 时,就会返回该静态页面——README 称之为"当请求匹配不到任何内容时返回静态页"("Return a static page when your request does not match anything else")。

回退到 Razor Page(new-routing-9)

new-routing-9/Program.cs 用 MapFallbackToPage("/Index") 把未匹配请求回退到 Razor Pages 的 /Index 页面:

app.MapRazorPages();
app.MapGet("/contact/us", async context => { /* ... */ });
app.MapFallbackToPage("/Index");

注意 MapFallbackToPage 要求已通过 services.AddRazorPages() 注册 Razor Pages 服务,回退目标必须是存在的页面路径。

Endpoint 与中间件:从 HttpContext 获取端点信息

HttpContext.GetEndpoint()(new-routing-10)

new-routing-10/Program.cs 演示在自定义中间件中调用 HttpContext.GetEndpoint() 扩展方法获取"正在被执行的当前端点":

Endpoint endPoint = httpContext.GetEndpoint();
if (endPoint.DisplayName == "/about")
{
    httpContext.Items.Add("GreetingFromMiddleWare", "Hello world from GreetingMiddleware");
}
await _next.Invoke(httpContext);

中间件通过判断 DisplayName 决定是否为请求附加数据;Razor 页面 Pages/about.cshtml 再通过 @HttpContext.Items["GreetingFromMiddleWare"] 把该数据渲染到页面。这是"中间件感知当前端点"("examine the current endpoint that is being executed")的典型应用。

Endpoint.Metadata.GetMetadata()(new-routing-11)

new-routing-11/Program.cs 展示了更正式的做法:自定义特性 MessageAttribute,在 Razor Page 的 Model 类上标注,然后中间件用 endPoint.Metadata.GetMetadata<MessageAttribute>() 取出:

var message = endPoint.Metadata.GetMetadata<MessageAttribute>();
if (message != null)
{
    httpContext.Items.Add("GreetingFromMiddleWare", message.Content);
}

about.cshtml.cs 中特性标注在 PageModel 类上:

[Message(Content = "Hello world message from attribute")]
public class AboutModel : PageModel
{ /* ... */ }

要点:Razor Pages 中特性必须放在 Model 类上,因为端点元数据来自页面模型类,而非页面方法。

按请求方法区分元数据(new-routing-12)

new-routing-12/Program.cs 进一步展示"根据请求方法返回不同元数据"的处理。由于 Razor Page 无法在方法级别使用特性(只能用于 Model 类),示例让 MessageAttribute 同时携带 ContentGet 与 ContentPost 两个属性,并在中间件中按 HttpContext.Request.Method 判断取哪个:

if (httpContext.Request.Method == HttpMethods.Get)
    httpContext.Items.Add("GreetingFromMiddleWare", message.ContentGet);
else if (httpContext.Request.Method == HttpMethods.Post)
    httpContext.Items.Add("GreetingFromMiddleWare", message.ContentPost);

对应的 about.cshtml.cs 用命名参数赋值两个属性,页面的 OnGet/OnPost 分别读取 HttpContext.Items。README 指出这与 MVC 不同——Razor Page 只能从 Model 类上取特性,导致"为每个请求取得恰当元数据需要额外步骤"。

MVC 控制器动作的元数据(new-routing-13)

与 Razor Page 不同,MVC 控制器可以在 Action 方法上直接标注特性。 new-routing-13/Controllers/HomeController.cs 中,[Message("...")] 分别标注在 GET 与 POST 的 About / AboutPost 动作上:

[HttpGet("about")]
[Message("Hello World from the GreetingFromMiddleWare[GET]")]
public IActionResult About() { /* ... */ }

[HttpPost("about")]
[Message("Hello World from the GreetingFromMiddleWare[POST]")]
public IActionResult AboutPost() { /* ... */ }

中间件 new-routing-13/Program.cs 的读取逻辑与 Razor Page 版本一致,通过 endPoint.Metadata.GetMetadata<MessageAttribute>() 获取并写入 HttpContext.Items。由于每个动作都是独立端点,MVC 天然能把"动作级特性"映射为"端点级元数据"。

IEndpointFeature 与 GetEndpoint 的等价性(new-routing-14)

new-routing-14/Program.cs 展示了获取端点信息的底层机制——通过 IFeatureCollection 直接取出 IEndpointFeature:

var feature = context.Features.Get<IEndpointFeature>();
await context.Response.WriteAsync($"Endpoint Name {feature.Endpoint.DisplayName}");

README 指出这与 HttpContext.GetEndpoint() 是等价的("You can accomplish the same thing using HttpContext.GetEndpoint"):GetEndpoint() 扩展方法内部就是访问 IEndpointFeature 的 Endpoint 属性,了解这一点有助于理解端点信息在请求特性集合(Feature)中的承载方式。

为内联中间件附加元数据(new-routing-15)

new-routing-15/Program.cs 演示 IEndpointConventionBuilder.WithMetadata:在 MapGet 返回的约定构建器上直接给端点挂上元数据对象:

app.MapGet("/", async context =>
{
    var endpoint = context.GetEndpoint();
    var greeting = endpoint.Metadata.GetMetadata<HelloWorld>();
    await context.Response.WriteAsync($"Greeting from metadata : {greeting.Greeting}");
}).WithMetadata(new HelloWorld { Greeting = "Hello World" });

WithMetadata 允许把任意对象(此处是自定义 HelloWorld 类实例)附加到端点,之后在端点处理逻辑中通过 GetMetadata<HelloWorld>() 取回。这为内联中间件/极简 API 提供了轻量级的元数据注入手段。

MVC / Razor Pages 的服务注册组合

这一组示例澄清了三个容易混淆的服务注册 API 之间的差异(README 对应 new-routing-17 至 19):

注册方式 能力 适用场景
services.AddControllers() 仅 MVC 控制器(API),无 Views、无 Razor Pages 纯 Web API(见 new-routing-17/Program.cs)
services.AddControllersWithViews() MVC 控制器 + Views,无 Razor Pages 经典 MVC(见 new-routing-18/Program.cs)
services.AddRazorPages() Razor Pages + MVC API(ControllerBase 可用),无 MVC Views Razor Pages 为主、附带少量 API(见 new-routing-19/Program.cs)

以 new-routing-19 为例,Program.cs 同时调用 app.MapControllers() 与 app.MapRazorPages(),并定义了一个 ControllerBase 派生控制器提供 JSON API:

[Route("/API/Message")]
public class APIController : ControllerBase
{
    [HttpGet("")]
    public ActionResult GetMessage()
    {
        return Ok(new { Message = "services.AddRazorPages() add supports for Razor Pages and MVC API. There is no MVC Views support." });
    }
}

约定路由:MapControllerRoute(new-routing-20)

new-routing-20/Program.cs 使用 IEndpointRouteBuilder.MapControllerRoute 手动配置多条约定路由,每条路由有自己的名称、模板与默认值:

app.MapControllerRoute("Admin", "Admin", new { Controller = "Admin", Action = "Index" });
app.MapControllerRoute("About", "About", new { Controller = "Home", Action = "About" });
app.MapControllerRoute("Default", "{controller=Home}/{action=Index}/{id?}");

与 new-routing-3 的 MapDefaultControllerRoute 相比,这里展示了如何自定义任意数量的命名约定路由——README 称之为"使用 IEndpointRouteBuilder.MapControllerRoute 配置基于约定的路由"。

Areas:按约定映射控制器区域(new-routing-16)

new-routing-16/Program.cs 演示 IEndpointRouteBuilder.MapAreaControllerRoute 为每个 Area 配置独立路由:

app.MapAreaControllerRoute("AdminArea", "Admin", "Admin/{controller=Home}/{action=Index}/{id?}");
app.MapAreaControllerRoute("CustomerArea", "Customer", "Customer/{controller=Home}/{action=Index}/{id?}");
app.MapDefaultControllerRoute();

注意源码中的注释提醒:Area 名称必须与控制器上 <a href="https://link.gitcode.com/i/d7dff6299b3e34f3cc5f702b99ae7a89" target="_blank">Area("Admin")] 特性声明的一致。见 [Areas/Admin/Controllers/HomeController.cs:

[Area("Admin")]
public class HomeController : Controller
{
    public ActionResult Index() => View();
    public ActionResult About() => Content("About");
}

高级端点配置:健康检查、Kestrel 默认协议与 Host 匹配

用 MapHealthChecks 配置健康检查(new-routing-21)

new-routing-21/Program.cs 展示端点路由时代的新健康检查用法:

builder.Services.AddHealthChecks();
var app = builder.Build();
app.MapHealthChecks("/WhatsUp");

README 强调这是"配置健康检查的新方式"——用 IEndpointRouteBuilder.MapHealthChecks 取代旧式的 IApplicationBuilder.UseHealthChecks,健康检查因此成为一个普通端点,可与其余路由共存于同一路由表。

配置 Kestrel 端点默认协议为 HTTP/2(new-routing-22)

new-routing-22/Program.cs 通过 KestrelServerOptions.ConfigureEndpointDefaults 让所有 Kestrel 监听端点只运行 HTTP/2:

builder.WebHost.ConfigureKestrel(k =>
{
    k.ConfigureEndpointDefaults(e =>
    {
        e.Protocols = HttpProtocols.Http2;
    });
});

该示例页面还提示:HTTP/2 只能通过 HTTPS 连接在浏览器中访问("It is only accessible from the browser over HTTPS connection")。

Host Matching:按主机名返回不同内容(new-routing-23)

new-routing-23/Program.cs 让同一个 / 路径根据访问主机返回不同内容。Kestrel 同时监听 localhost:8111 与 localhost:8112,再用 RequireHost 分别限定端点:

builder.WebHost.ConfigureKestrel(k =>
{
    k.ListenLocalhost(8111);
    k.ListenLocalhost(8112);
});

app.MapGet("/", async context =>
{
    await context.Response.WriteAsync("hello world from http://localhost:8111");
}).RequireHost("localhost:8111");

app.MapGet("/", async context =>
{
    await context.Response.WriteAsync("hello world from http://localhost:8112");
}).RequireHost("localhost:8112");

该示例的 README.md 建议用 dotnet watch run 启动,然后分别访问两个端口观察差异。

用 WithMetadata + HostAttribute 实现等价效果(new-routing-24)

new-routing-24/Program.cs 产生与 new-routing-23 完全相同的效果,但实现方式不同:使用 IEndpointConventionBuilder.WithMetadata 配合 HostAttribute,而不是 RequireHost:

app.MapGet("/", async context => { /* ... */ }).WithMetadata(new HostAttribute("localhost:8111"));

README 明确说明这是上一示例的等价实现("This produces the same exact effect as the previous example"),这也再次印证了 RequireHost 在底层也是通过向端点元数据添加 HostAttribute 来生效的。

动态路由:DynamicRouteValueTransformer

MVC 动态路由(new-routing-25)

new-routing-25/Program.cs 演示 MapDynamicControllerRoute<T> + DynamicRouteValueTransformer:路由模板 {number} 先匹配任意一段路径,再由转换器把它翻译成具体的控制器与动作。

转换器必须先注册为单例服务(builder.Services.AddSingleton<NumberTransformer>()),随后用 MapDynamicControllerRoute<NumberTransformer>("{number}") 注册动态路由:

public class NumberTransformer : DynamicRouteValueTransformer
{
    public override ValueTask<RouteValueDictionary> TransformAsync(HttpContext httpContext, RouteValueDictionary values)
    {
        if (!values.ContainsKey("number"))
            return new ValueTask<RouteValueDictionary>(values);

        values["controller"] = "Home";
        var action = values["number"] switch
        {
            "1" => "one",
            "2" => "two",
            "3" => "three",
            _ => "undefined"
        };
        values["action"] = action;
        return new ValueTask<RouteValueDictionary>(values);
    }
}

这样 /1、/2、/3 分别路由到 HomeController 的 One、Two、Three 动作,其余值落到 Undefined 动作——路由目标完全由运行期数据决定,这就是"动态处理 MVC 路由"("Handle MVC routing dynamically")的含义。

Razor Pages 动态路由(new-routing-26)

new-routing-26/Program.cs 展示了面向 Razor Pages 的对应方案 MapDynamicPageRoute<T>:转换器不再设置 controller/action,而是设置 page 路由值:

var page = values["number"] switch
{
    "1" => "/one",
    "2" => "/two",
    "3" => "/three",
    _ => "/undefined"
};
values["page"] = page;

页面目录 Pages 下存在 One.cshtml、Two.cshtml、Three.cshtml 与 Undefined.cshtml 与之对应,/1、/2、/3 及任意其他值会被动态映射到这些页面。

Razor Pages Areas:路由、映射与回退

创建 Razor Pages Areas(new-routing-28)

new-routing-28/Program.cs 是最基础的 Areas 配置——AddRazorPages() + MapRazorPages(),其余靠约定目录结构生效:

builder.Services.AddRazorPages();
var app = builder.Build();
app.MapRazorPages();
app.Run();

Area 目录结构遵循 Areas/<AreaName>/Pages/... 的约定,例如 Areas/Admin/Pages/Index.cshtml。Razor Pages 的 Area 无需像 MVC 那样写 [Area] 特性,目录位置本身就决定了它属于哪个 Area。

把路由映射到 Area 中的页面(new-routing-27)

new-routing-27/Program.cs 用 RazorPagesOptions.Conventions.AddAreaPageRoute 为 Area 内的页面注册额外路由:

builder.Services.AddRazorPages(x =>
{
    x.Conventions.AddAreaPageRoute("Admin", "/Index", "/Manage");
    x.Conventions.AddAreaPageRoute("Customer", "/Index", "/CustomerService");
});

AddAreaPageRoute(areaName, pagePath, route) 的三个参数分别是 Area 名、页面路径(如 "/Index")与要附加的公开路由模板(如 "/Manage")。这样 <a href="https://link.gitcode.com/i/8936af9ddf43a9a57c2e776620b01690" target="_blank">Areas/Admin/Pages/Index.cshtml</a> 既可通过默认 Area 路由访问,也可通过 /Manage 直达。

Area 中的回退页面(new-routing-29)

new-routing-29/Program.cs 使用 MapFallbackToAreaPage 把未匹配请求回退到指定 Area 的页面:

app.MapRazorPages();
app.MapFallbackToAreaPage("/Other", "Admin");

MapFallbackToAreaPage(page, area) 第一个参数是回退目标页面路径,第二个是 Area 名。入口页面 Pages/Index.cshtml 提供了一组测试链接,并提示"回退页面只对不带扩展名的非文件名路由生效"("Fallback page only works for non file name route (e.g. without extensions)")。

按路由模式匹配返回不同回退页面(new-routing-30)

new-routing-30/Program.cs 进阶演示:根据请求命中的路由模式,把回退目标分流到不同页面:

app.MapRazorPages();
app.MapFallbackToAreaPage("/Other", "Admin");
app.MapFallbackToAreaPage("{segment}/{segment2}", "/OtherLevel", "Admin");
app.MapFallbackToAreaPage("{number:int}", "/OtherNumber", "Admin");

三层回退依次覆盖:任意单段路径回退 /Other、两段路径回退 /OtherLevel、单段整型路径回退 /OtherNumber(对应 Areas/Admin/Pages/Other.cshtml 等页面)。{number:int} 使用了路由约束,说明回退路由同样支持约束语法——这就是"根据匹配请求的路由模式返回不同的回退页面"("return different fallback page located in areas depending on the route pattern that matches the request")。

端点级匿名访问与授权(new-routing-31)

new-routing-31/Program.cs 展示在端点路由中控制认证/授权。先注册 Cookie 认证与授权服务,并在管线中加入 UseAuthentication / UseAuthorization:

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options => { options.LoginPath = new PathString("/login"); });
builder.Services.AddAuthorization();

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/", async context => { /* ... */ }).AllowAnonymous();
app.MapGet("/login", async context => { /* ... */ });
app.MapGet("/protected", async context => { /* ... */ }).RequireAuthorization();

AllowAnonymous() 允许匿名访问首页,RequireAuthorization() 强制 /protected 必须登录,未登录用户会被重定向到配置的 /login 路径。这两个 API 都是 IEndpointConventionBuilder 提供的约定方法,是端点路由下"按端点粒度控制访问"("Allow anonymous access and require authorization to endpoints")的标准做法。

参数转换器(Parameter Transformer):控制路由令牌生成

parameter-transformer/Program.cs 演示了 IOutboundParameterTransformer 与 RouteTokenTransformerConvention:在生成 URL 时,把路由模板中的 [controller]、[action] 令牌替换成转换后的文本(例如 PascalCase 动作名变成 kebab-case):

builder.Services.AddMvc(options =>
{
    options.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer()));
});

public class SlugifyParameterTransformer : IOutboundParameterTransformer
{
    public string TransformOutbound(object value)
    {
        if (value == null) return null;
        return Regex.Replace(value.ToString(), "([a-z])([A-Z])", "$1-$2").ToLower();
    }
}

该转换器用正则 ([a-z])([A-Z]) 在大小写交界处插入连字符并转小写,因此 AboutUs 变成 about-us、OrderItemsNow 变成 order-items-now。README 特别提醒:转换只作用于令牌替换([controller]、[action]),显式写在 [Route("WeAreAmazing")] 等属性中的字面路径不受影响——示例中的 Random 动作就保留了原始路由 /WeAreAmazing。控制器类名上的 [controller] 令牌同样会被转换(GetThisOffersNowController → get-this-offers-now)。

补充:LinkGenerator 生成端点链接(endpoint-routing 系列)

仓库中 endpoint-routing 至 endpoint-routing-6 五个目录补充演示了与端点路由配套的 LinkGenerator 链接生成能力,可在中间件中基于路由信息反向生成 URL:

  • endpoint-routing-2/Program.cs:linkGenerator.GetUriByAction(context, controller: "Hello", action: "World") 生成完整 URI;
  • endpoint-routing-3/Program.cs:为多个控制器/动作批量生成 URL,并演示"无法推导控制器与动作信息时不会产生链接"(生成结果为 null)的边界行为;
  • endpoint-routing-4/Program.cs:通过 values 参数传入路由值(name、age、isNice 等),并利用 {age:int}、{isNice:bool}、{danger:required} 等路由约束参与链接生成;
  • endpoint-routing-6/Program.cs:linkGenerator.GetPathByAction(...) 生成相对路径而非完整 URI,适合站内链接场景。

这四个示例体现了端点路由的一个关键红利:端点信息集中注册后,LinkGenerator 可以脱离请求管线独立执行 URL 生成,这也是 new-routing-10~15 中中间件注入 LinkGenerator 的原因。

运行方式与注意事项

  • 运行:每个示例目录都是独立项目,进入对应目录执行 dotnet run 即可;Host Matching 示例建议用 dotnet watch run(见 new-routing-23/README.md)。
  • 目标框架:示例均面向 net10.0(见 new-routing.csproj 与 endpoint-routing-4.csproj),运行环境需安装对应 .NET SDK。
  • HTTP/2 示例:new-routing-22 将 Kestrel 默认协议设为 HTTP/2 后,浏览器访问需走 HTTPS(详见 new-routing-22/Program.cs 页面说明)。
  • 路由注册顺序:回退路由(MapFallbackTo*)语义上位于路由匹配的最末位,仅当其他端点都不匹配时才生效(参见 new-routing-8/9/29/30 的实现)。
  • 动态路由前置条件:MapDynamicControllerRoute<T> / MapDynamicPageRoute<T> 使用的转换器必须以单例注册进 DI(见 new-routing-25/Program.cs)。

小结

通过本仓库 32 个端点路由示例,可以完整掌握 ASP.NET Core 端点路由的实践全貌:从最基础的 Razor Pages / MVC / RequestDelegate 端点映射,到 MapMethods、MapFallbackToFile/Page/AreaPage 等条件映射与回退策略;从 HttpContext.GetEndpoint()、Endpoint.Metadata.GetMetadata<T>()、IEndpointFeature 的端点内省与元数据传递,到 MapAreaControllerRoute、MapDynamicControllerRoute、RouteTokenTransformerConvention 等进阶主题,最后覆盖 Host 匹配、端点级认证授权与 LinkGenerator 链接生成。每一个示例都可直接作为日常开发的起点,在 projects/endpoint-routing 目录下按需查阅与运行。

登录后查看全文
practical-aspnetcore