How would you implement a catch-all route parameter to handle a variable-depth URL path, like a file browser or wiki-style page hierarchy?
Short answer
A catch-all route parameter, denoted with an asterisk prefix ({*path}), captures the remainder of the URL path (including any slashes) as a single string value, rather than requiring an exact number of fixed segments -- useful for hierarchical resources like nested file paths or…
Advertisement
AModel answer
A catch-all route parameter, denoted with an asterisk prefix ({*path}), captures the remainder of the URL path (including any slashes) as a single string value, rather than requiring an exact number of fixed segments -- useful for hierarchical resources like nested file paths or wiki pages where the depth isn't fixed in advance.
app.MapGet("/wiki/{*pagePath}", (string pagePath) => {
// GET /wiki/programming/csharp/generics -> pagePath = "programming/csharp/generics"
return GetWikiPage(pagePath);
});Real-world example
A documentation site's wiki feature uses a catch-all route to support arbitrarily nested page hierarchies (/wiki/category/subcategory/page-name) without needing to register a separate route template for every possible nesting depth.
Likely follow-ups
- How does URL encoding of slashes within a catch-all segment get handled?
- What are the security implications of accepting arbitrary path-like input this way (path traversal)?
Related topics