Route templates
A web program decides what to do from the path of the address. A route template describes such a path with named parts — users/{id}/orders/{orderId?} — and the routing classes of ASP.NET Core match paths against it and read the values. This lesson uses them with required, optional, default and catch-all parts, and chooses between several routes.
What you will learn#
- the syntax of a route template,
- required parts, optional parts (
?), default values (=), catch-all parts (*), TemplateParserandTemplateMatcher,- reading the values of the parts,
- why the order of routes matters,
- what a template does not do.
The tutorial A web service with a database and the tutorial A tiny web framework made small web servers with simple routes. Real programs have many routes with parts that change (/users/42, /users/43). Templates are the standard way to write them, and the same classes work in your own Ring program.
The routing classes are part of the ASP.NET Core runtime, so the program has "RingDotNet.Web" in its using { } (Getting started).
The program#
# route templates - "users/{id}/orders/{orderId?}", optional and default values, catch-all parameters, and choosing a route
load "dotnet.ring"
using {
"Microsoft.AspNetCore.Routing.Template"
"Microsoft.AspNetCore.Routing"
"System"
"RingDotNet.Web" # the routing classes are part of the ASP.NET Core runtime: this line starts it
}
func main
# A web program decides what to do from the PATH of the address: /users/42 shows user 42, /files/docs/a/b.txt shows a file. A ROUTE
# TEMPLATE describes such a path with named parts in braces. ASP.NET Core uses them for every route; the same classes work here.
# {id} a required part, its value is read into "id"
# {orderId?} an optional part
# {page=1} a part with a default value
# {*path} the catch-all: everything that is left, with its slashes
# {id:int} a constraint (a router checks it: only whole numbers): the template keeps it as a name
? "1. the templates and their parts:"
for cRoute in ["users/{id}/orders/{orderId?}","products/{category}/{page=1}","files/{*path}","items/{id:int}"]
oTemplate = (new TemplateParser).Parse(cRoute)
cParts = ""
aParts = oTemplate.Parameters.toList()
for oPart in aParts
cKind = "required"
if oPart.IsOptional
cKind = "optional"
ok
if oPart.IsCatchAll
cKind = "catch-all"
ok
xDefault = oPart.DefaultValue # a text, or the null object when there is no default
if not isObject(xDefault)
cKind = "default " + xDefault
ok
cParts += oPart.Name + " (" + cKind + ") "
next
? " " + padRight(cRoute,32) + cParts
next
# 2. Matching a path. TryMatch answers yes or no and fills a dictionary with the values of the parts.
? nl + "2. users/{id}/orders/{orderId?} against some paths:"
for cPath in ["/users/42/orders/7","/users/42/orders","/users/42","/users/42/orders/7/extra","/USERS/5/ORDERS/9"]
? " " + padRight(cPath,28) + showMatch("users/{id}/orders/{orderId?}",cPath)
next
# 3. Defaults and the catch-all
? nl + "3. products/{category}/{page=1}:"
for cPath in ["/products/shoes","/products/shoes/3"]
? " " + padRight(cPath,28) + showMatch("products/{category}/{page=1}",cPath)
next
? nl + " files/{*path} takes the rest of the path, with its slashes:"
for cPath in ["/files/readme.txt","/files/docs/guide/intro.md"]
? " " + padRight(cPath,28) + showMatch("files/{*path}",cPath)
next
# 4. A list of routes: the program tries them in order and uses the first that matches. Put the most specific routes first.
aTable = [ ["users/{id}/orders/{orderId?}","show the orders of a user"], ["users/{id}","show a user"], ["files/{*path}","send a file"], ["{page}","show a page"] ]
? nl + "4. which route handles which path:"
for cPath in ["/users/42","/users/42/orders/7","/files/a/b.png","/about","/users"]
? " " + padRight(cPath,24) + chooseRoute(aTable,cPath)
next
# the dictionary of values for a template and a path, as text; "no match" when the path does not fit the template
func showMatch cTemplate,cPath
oValues = new RouteValueDictionary
if not matches(cTemplate,cPath,oValues)
return "no match"
ok
cText = ""
aKeys = sort(oValues.Keys.toList())
for cKey in aKeys
cText += cKey + " = " + oValues.Item(cKey) + " "
next
return "match " + cText
func matches cTemplate,cPath,oValues
oTemplate = (new TemplateParser).Parse(cTemplate)
# the defaults of the template ({page=1}) are given to the matcher: a part with a default may be missing at the END of the path
oDefaults = new RouteValueDictionary
aParts = oTemplate.Parameters.toList()
for oPart in aParts
xDefault = oPart.DefaultValue
if not isObject(xDefault)
oDefaults.Add(oPart.Name,xDefault)
ok
next
oMatcher = new TemplateMatcher(oTemplate,oDefaults)
return oMatcher.TryMatch((new PathString).@New(cPath),oValues)
func chooseRoute aTable,cPath
for aRoute in aTable
oValues = new RouteValueDictionary
if matches(aRoute[1],cPath,oValues)
return aRoute[1] + " -> " + aRoute[2]
ok
next
return "(no route: 404 not found)"
func padRight cText,nWidth
return cText + copy(" ",nWidth - len(cText))1. the templates and their parts:
users/{id}/orders/{orderId?} id (required) orderId (optional)
products/{category}/{page=1} category (required) page (default 1)
files/{*path} path (catch-all)
items/{id:int} id (required)
2. users/{id}/orders/{orderId?} against some paths:
/users/42/orders/7 match id = 42 orderId = 7
/users/42/orders match id = 42
/users/42 no match
/users/42/orders/7/extra no match
/USERS/5/ORDERS/9 match id = 5 orderId = 9
3. products/{category}/{page=1}:
/products/shoes match category = shoes page = 1
/products/shoes/3 match category = shoes page = 3
files/{*path} takes the rest of the path, with its slashes:
/files/readme.txt match path = readme.txt
/files/docs/guide/intro.md match path = docs/guide/intro.md
4. which route handles which path:
/users/42 users/{id} -> show a user
/users/42/orders/7 users/{id}/orders/{orderId?} -> show the orders of a user
/files/a/b.png files/{*path} -> send a file
/about {page} -> show a page
/users {page} -> show a pageThis program uses a few generic functions (dnNew, dnStatic, callMethod, getProp) where a class cannot be used. The lesson The generic functions explains them.
How it works#
The syntax#
A template is a path whose parts are either literal text (users, orders: matched without regard to case) or parameters in braces:
| Written | Meaning |
|---|---|
{id} | required: one part of the path |
{orderId?} | optional: it may be missing at the end |
{page=1} | has a default value: it may be missing at the end, and then the value is 1 |
{*path} | catch-all: everything that is left, with its slashes |
{id:int} | has a constraint (here: a whole number) |
TemplateParser.Parse(text) reads a template into an object whose Parameters list each part with its Name, IsOptional, IsCatchAll and DefaultValue (a text, or the null object when there is no default). Step 1 prints them. The template items/{id:int} keeps the constraint as part of the parameter (InlineConstraints); a matcher does not apply constraints: the router that uses the template checks them afterwards (the program would test that id is a number before it uses it).
Matching#
TemplateMatcher is made from the template and a dictionary of defaults. TryMatch(path, values) answers yes or no and fills values (a RouteValueDictionary) with the part names and their values. The path is a PathString and must start with /. In step 2: /users/42/orders/7 matches with id = 42 and orderId = 7; /users/42/orders matches because orderId is optional (and gets no value); /users/42 does not match this template, because the literal part orders is missing; /users/42/orders/7/extra does not match because there is a part too many; and the capital letters in /USERS/5/ORDERS/9 do not matter.
Defaults are important for {page=1}: the matcher needs them in its dictionary, so the program copies the defaults of the parameters into one (oDefaults). With that, /products/shoes matches with page = 1, and /products/shoes/3 with page = 3. The values come back as text, even for numbers; convert them (number()) and check them.
The catch-all#
{*path} takes all the rest, including the slashes: /files/docs/guide/intro.md gives path = docs/guide/intro.md. It is used for files, proxies and single-page applications. Because it takes everything, the program that uses it must check the value (no .., no absolute path) before it opens a file (the tutorial Paths and the environment).
Many routes#
A program has a list of routes and uses the first one that matches, as in step 4. So the order is part of the program: put the most specific routes first and the general ones last. /users/42 goes to users/{id}, /users/42/orders/7 to the route with orders, and /about to {page}. Notice /users: it does not fit users/{id} (the id is missing), so it falls through to {page} and shows a page called users. A route users listed before {page} makes the choice explicit. When no route matches, the answer is 404 Not Found.
What a template does not do#
A template describes the path. It does not read the query string (?page=2, the tutorial URLs and encodings), the method (GET or POST), the headers or the body. A program matches the path first, then looks at the method and the rest. ASP.NET also uses the templates the other way round, to make addresses from values (TemplateBinder), so a link is never written by hand.
What you learned#
- templates with literal and parameter parts,
- optional (
?), default (=) and catch-all (*) parameters, TemplateParser,TemplateMatcherandRouteValueDictionary,- values are text and must be checked,
- the first matching route wins, so the order matters.
Exercises#
- Make the table of routes for a small shop (
/,/products,/products/{id},/cart,/checkout) and test ten paths. - Add a check to the
{id:int}route: refuse the match when the value is not a number. - Put the routes in the web server of the tutorial A tiny web framework and answer 404 when none matches.
- Write
isSafePath(value)for a catch-all{*path}and test../secret.txt.