Razor Pages锚点标签助手多参数失效及路由404问题问询
Hey Richard, let's break down your issues one by one and work through the fixes:
1. Why multi-parameter links generate empty href & how to fix it
The root problem here is the alpha constraint on your SicCode route parameter. The alpha constraint only allows uppercase/lowercase letters ([a-zA-Z])—when you pass a value like "10" (which is numeric), it doesn’t match the constraint. Razor Pages’ tag helper can’t find a valid matching route, so it outputs an empty href.
Since you need SicCode to be treated as a string regardless of whether it’s letters or numbers, replace the alpha constraint with string, or just omit the constraint (the default route parameter type is string):
// Option 1: Explicit string constraint @page "{ReportId:int}/{SicCode:string?}" // Option 2: Shorter, default string type @page "{ReportId:int}/{SicCode?}"
With this change, your multi-parameter link will generate correctly:
<a asp-page="/ReportSics" asp-route-ReportId="3" asp-route-SicCode="10">rss2</a>
Will output:
<a href="/Reports/ReportSics/3/10">rss2</a>
2. Why the other page with a non-optional second parameter fails to generate links
If your second page uses a route like @page "{ReportId:int}/{SicCode:alpha}" (non-optional), it’s hitting the same constraint issue. When you pass a SicCode that isn’t pure letters, the tag helper can’t match the route and returns an empty href.
Fix it the same way—swap alpha for string or remove the constraint. Also, note that if two pages have identical route templates (one with optional parameter, one without), you’ll create route ambiguity (Razor Pages can’t tell which page to match). To fix that, adjust one of the templates to add a unique prefix, e.g.:
// Optional parameter page @page "reports/{ReportId:int}/{SicCode?}" // Non-optional parameter page @page "reports/required/{ReportId:int}/{SicCode}"
3. Why Page/2/12 returns 404 but Page/2/M works
Again, this is the alpha constraint at play. The value 12 is numeric, which violates the alpha rule—so Razor Pages can’t find a matching page and returns a 404. The value M is a letter, so it fits the constraint and loads correctly.
The fix is identical to the above: replace alpha with string or remove the constraint entirely. This lets both letter and numeric values for SicCode match the route and load the page successfully.
内容的提问来源于stack exchange,提问作者Richard Barraclough

