- Modern Web Development with ASP.NET Core 3
- Ricardo Peres
- 350字
- 2021-06-18 18:35:58
Using route templates
A template is a relative URL, so it mustn't start with a slash (/). In it, you define the structure of your site, or, more accurately, the structure that you intend to make available. As ASP.NET Core is an MVC framework, the template should describe how to map the request to an action method in a controller. The following is the template:
{controller=Home}/{action=Index}/{id?}
It consists of sections separated by slashes, where each section has some tokens (inside curly braces).
Another example would be this:
sample/page
Here it is not clear what we want, as there are no mentions of controller or action. However, this is a perfectly valid template, and the required information needs to come from elsewhere.
A template can have the following elements:
- Alphanumeric literals
- String fragments inside curly braces ({}), which are named tokens and can be mapped to action method parameters
- Named tokens with equal assignments (=) have default values, in case the token is not supplied in the URL; it doesn't make sense to have a token with a default value followed by a required token without
- Tokens that end with a question mark (?), which are optional, meaning they are not required; optional tokens cannot be followed by required tokens
- Tokens that start with a star (*), which are entirely optional and match anything; they need to be the last element in the template
Tokens are always alphanumeric character segments and can be separated by separator symbols (/, ?, -, (, ), and so on). However, you don't need to use separators; the following is perfectly valid—notice the lack of a slash between the action and id tokens:
{controller=Admin}/{action=Process}{id}
Another slightly more complex example follows, which involves adding a catch-all token querystring:
{controller=Admin}/{action=Process}/{?id}?{*querystring}
This template will match the following URLs:

Yet another perfectly valid example would be this:
api/{controller=Search}/{action=Query}?term={term}
That would match the following:
api?term=.net+core
api/Search?term=java
api/Search/Query?term=php
Note that any literals must be present exactly the same way as shown, in the URL, regardless of the casing.
Now, let's see how the route parameters specified in templates are matched.
- 解構產品經理:互聯網產品策劃入門寶典
- WebAssembly實戰
- Rust編程從入門到實戰
- 技術領導力:程序員如何才能帶團隊
- The React Workshop
- Mastering Apache Spark 2.x(Second Edition)
- 算法訓練營:提高篇(全彩版)
- Yocto for Raspberry Pi
- Building RESTful Python Web Services
- Learning JavaScript Data Structures and Algorithms
- Unity 2D Game Development Cookbook
- 微信小程序開發實戰:設計·運營·變現(圖解案例版)
- ASP.NET求職寶典
- JavaScript Concurrency
- 你好!Java