Asp.net core razor pages中AddPageRoute如何传递querystring参数
问题原因
你之前的写法不生效是因为AddPageRoute方法的第一个参数仅接受Razor页面相对于Pages目录的纯路径,不能直接拼接querystring参数,路由系统无法识别这种写法,自然无法完成匹配。
实现方案
提供两种常用的实现方式,可根据自己的需求选择:
方式一:固定路由映射+传参(适合路由规则固定的场景)
步骤1:配置路由规则
在Program.cs中配置路由,直接给每个路径绑定对应的页面和固定参数:
var builder = WebApplication.CreateBuilder(args); // 添加Razor Pages服务 builder.Services.AddRazorPages(); var app = builder.Build(); // 静态文件、异常处理等中间件配置省略... app.MapRazorPages(); // 配置自定义路由映射 app.MapPageRoute("BlogRoute", "Blog", "~/WritingList", false, new RouteValueDictionary { { "typeID", "1" } }); app.MapPageRoute("NewsRoute", "News", "~/WritingList", false, new RouteValueDictionary { { "typeID", "2" } }); app.MapPageRoute("MobileRoute", "Mobile", "~/ProductList", false, new RouteValueDictionary { { "typeID", "3" } }); app.MapPageRoute("LaptopRoute", "Laptop", "~/ProductList", false, new RouteValueDictionary { { "typeID", "4" } }); app.Run();
步骤2:页面获取参数
在对应页面的PageModel中可以通过两种方式拿到传入的typeID:
- 方式A:属性绑定
public class WritingListModel : PageModel { [BindProperty(SupportsGet = true)] public int TypeID { get; set; } public void OnGet() { // 直接使用TypeID即可获取对应值 } }
- 方式B:从RouteData读取
public void OnGet() { if (RouteData.Values.TryGetValue("typeID", out var typeIdVal) && int.TryParse(typeIdVal?.ToString(), out int typeId)) { // 拿到typeId处理业务逻辑 } }
方式二:正则路由模板匹配(适合同组路由规则统一配置的场景)
如果后续要新增同类型路由,不需要重复加配置,只需要修改正则规则即可:
步骤1:配置路由
builder.Services.AddRazorPages() .AddRazorPagesOptions(options => { // 匹配Blog、News到WritingList页面 options.Conventions.AddPageRoute("/WritingList", "{contentType:regex(^(Blog|News)$)}"); // 匹配Mobile、Laptop到ProductList页面 options.Conventions.AddPageRoute("/ProductList", "{productType:regex(^(Mobile|Laptop)$)}"); });
步骤2:页面获取参数并映射typeID
public class WritingListModel : PageModel { [BindProperty(SupportsGet = true)] public string ContentType { get; set; } public void OnGet() { var typeID = ContentType.ToLower() switch { "blog" => 1, "news" => 2, _ => 0 // 异常值处理 }; } }
内容的提问来源于stack exchange,提问作者msn.secret
相关产品推荐
相关产品推荐

